PHP Session & PHP Cookies with Example

โšก Smart Summary

Cookies and Sessions in PHP both preserve state across the stateless HTTP protocol, but store data differently. This walkthrough explains how cookies save small files on the client, how sessions keep data on the server, and how to create, read, and destroy each with working code.

  • ๐Ÿช What Cookies Are: A cookie is a small file, up to 4KB, that the server stores on the client and that returns with every later request.
  • ๐Ÿ—„๏ธ What Sessions Are: A session stores data on the server under a unique ID, kept in the $_SESSION array and referenced by a session cookie.
  • ๐Ÿ†š Key Difference: Cookies live on the client and suit small, non-sensitive data; sessions live on the server and hold larger or private data.
  • ๐Ÿ› ๏ธ Creating Cookies: setcookie() sets a name, value, and optional expiry, path, domain, secure, and httponly flags before any HTML output.
  • ๐Ÿ“ Creating Sessions: session_start() begins a session, after which you read and write values through the $_SESSION superglobal array.
  • ๐Ÿ—‘๏ธ Cleaning Up: Expire a cookie by setting a past time; end a session with session_destroy() or clear one value with unset().
  • ๐Ÿค– AI Assist: AI tools can implement secure session handling and flag cookie or session weaknesses in existing PHP code.

PHP Cookies and Sessions

What is Cookie?

A cookie is a small file with a maximum size of 4KB that the web server stores on the client computer.

Once a cookie has been set, all page requests that follow return the cookie name and value.

A cookie can only be read from the domain that it has been issued from. For example, a cookie set using the domain www.guru99.com cannot be read from the domain career.guru99.com.

Most of the websites on the internet display elements from other domains such as advertising. The domains serving these elements can also set their own cookies. These are known as third party cookies.

A cookie created by a user can only be visible to them. Other users cannot see its value.

Most web browsers have options for disabling cookies, third party cookies, or both.

If this is the case, then PHP responds by passing the cookie token in the URL.

The diagram shown below illustrates how cookies work.

What is Cookie

Here,

1) A user requests a page that stores cookies

2) The server sets the cookie on the user’s computer

3) Other page requests from the user will return the cookie name and value

Why and when to use Cookies?

  • HTTP is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user’s computer. The path where the cookies are stored depends on the browser. Internet Explorer usually stores them in the Temporary Internet Files folder.
  • Personalizing the user experience โ€“ this is achieved by allowing users to select their preferences. The page requests that follow are personalized based on the preferences set in the cookies.
  • Tracking the pages visited by a user

Creating Cookies

Let us now look at the basic syntax used to create a cookie.

<?php

setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);

?>

HERE,

  • “setcookie” is the PHP function used to create the cookie.
  • “cookie_name” is the name of the cookie that the server will use when retrieving its value from the $_COOKIE array variable. It is mandatory.
  • “cookie_value” is the value of the cookie and it is mandatory.
  • “[expiry_time]” is optional; it can be used to set the expiry time for the cookie, such as 1 hour. The time is set using the PHP time() function plus or minus a number of seconds greater than 0, i.e. time() + 3600 for 1 hour.
  • “[cookie_path]” is optional; it can be used to set the cookie path on the server. The forward slash “/” means that the cookie will be made available on the entire domain. Sub directories limit the cookie access to the subdomain.
  • “[domain]” is optional; it can be used to define the cookie access hierarchy, i.e. www.cookiedomain.com means the entire domain while www.sub.cookiedomain.com limits the cookie access to www.sub.cookiedomain.com and its sub domains.
  • “[secure]” is optional; the default is false. It is used to determine whether the cookie is sent via HTTPS if it is set to true, or HTTP if it is set to false.
  • “[httponly]” is optional. If it is set to true, then client side scripting languages such as JavaScript cannot access the cookie.

Note: the PHP setcookie function must be executed before the HTML opening tag.

Let us now look at an example that uses cookies.

We will create a basic program that allows us to store the user name in a cookie that expires after sixty seconds.

The code below shows the implementation of the above example “cookies.php”.

<?php
setcookie("user_name", "Guru99", time()+ 60,'/'); // expires after 60 seconds
echo 'the cookie has been set for 60 seconds';
?>

Output:

the cookie has been set for 60 seconds

Retrieving the Cookie value

Create another file named “cookies_read.php” with the following code.

<?php
print_r($_COOKIE); // output the contents of the cookie array variable
?>

Output:

Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [user_name] => Guru99 )

Note: $_COOKIE is a PHP built-in superglobal variable. It contains the names and values of all the set cookies.

The number of cookies and their size is limited by the browser, typically around 50 cookies per domain and 4KB per cookie.

Testing our application. Let us assume you have saved your PHP files in a phptuts folder.

  • Step 1 โ€“ open your web browser and enter the URL http://localhost/phptuts/cookies_read.php

Retrieving the Cookie value

Note: Only an empty array has been displayed

  • Step 2 โ€“ browse to the URL http://localhost/phptuts/cookies.php

Retrieving the Cookie value

  • Step 3 โ€“ switch back to the first tab, then click on the refresh button

Retrieving the Cookie value

Wait for a minute, then click on the refresh button again. What results did you get?

Delete Cookies

  • If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that has already passed.
  • Create a new file named cookie_destroy.php with the following code
<?php

setcookie("user_name", "Guru99", time() - 360,'/');

?>
  • Repeat steps 1 through 3 from the above section on retrieving cookie values.
  • Open the URL http://localhost/phptuts/cookie_destroy.php
  • Switch to the URL http://localhost/phptuts/cookies_read.php. What results does it display?

What is a Session?

  • A session is a global variable stored on the server.
  • Each session is assigned a unique id which is used to retrieve stored values.
  • Whenever a session is created, a cookie containing the unique session id is stored on the user’s computer and returned with every request to the server. If the client browser does not support cookies, the unique PHP session id is displayed in the URL.
  • Sessions have the capacity to store relatively large data compared to cookies.
  • The session values are automatically deleted when the browser is closed. If you want to store the values permanently, then you should store them in the database.
  • Just like the $_COOKIE array variable, session variables are stored in the $_SESSION array variable. Just like cookies, the session must be started before any HTML tags.

Why and when to use Sessions?

  • You want to store important information such as the user id more securely on the server where malicious users cannot tamper with it.
  • You want to pass values from one page to another.
  • You want an alternative to cookies on browsers that do not support cookies.
  • You want to store global variables in an efficient and more secure way compared to passing them in the URL.
  • You are developing an application such as a shopping cart that has to temporarily store information with a capacity larger than 4KB.

Creating a Session

In order to create a session, you must first call the PHP session_start function and then store your values in the $_SESSION array variable.

Let us suppose we want to know the number of times that a page has been loaded. We can use a session to do that.

The code below shows how to create and retrieve values from sessions.

<?php

session_start(); // start the session

if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];

?>

Output:

You are visitor number 1

Destroying Session Variables

The session_destroy() function is used to destroy the whole PHP session.

If you want to destroy only a single session item, you use the unset() function.

The code below illustrates how to use both methods.

<?php

session_destroy(); // destroy entire session

?>
<?php

unset($_SESSION['product']); // destroy product session item

?>

session_destroy removes all the session data, including cookies associated with the session.

unset only frees the individual session variables. Other data remains intact.

FAQs

Cookies store data in a small file on the user’s browser and travel with every request. Sessions store data on the server and only send a session ID cookie. Sessions are safer for sensitive or larger data.

By default, PHP saves session data as files in the path set by session.save_path in php.ini, often the system temp directory. High-traffic sites often switch this to a database, Redis, or Memcached handler.

Set the HttpOnly flag so JavaScript cannot read the cookie, the Secure flag so it travels only over HTTPS, and a SameSite attribute to limit cross-site sending. For sessions, regenerate the ID after login.

Yes. AI can generate a login flow that regenerates the session ID, sets secure cookie flags, stores minimal data server side, and enforces timeouts. Review the output against your security requirements.

Yes. AI can scan for missing HttpOnly or Secure flags, session fixation risks, storing sensitive data in cookies, and absent ID regeneration after login, then suggest the corrected code.

Summarize this post with: