Cookies in PHP

Table of Contents

  • Introduction to Cookies
  • Setting Cookies in PHP
  • Retrieving Cookies in PHP
  • Modifying and Unsetting Cookies
  • Cookie Expiration and Lifetime
  • Secure Cookies and HttpOnly Cookies
  • Cookie Scope: Domain and Path
  • Practical Example: Remember Me Functionality
  • Troubleshooting Common Cookie Issues
  • Summary

Introduction to Cookies

Cookies are small pieces of data that are stored on a user’s browser by the server. They are sent with every HTTP request, which makes them useful for storing information about the user or their session. Unlike sessions, which store data on the server, cookies store data on the client side.

Cookies are commonly used for:

  • Remembering user preferences.
  • Storing authentication details (e.g., “Remember Me” functionality).
  • Tracking user behavior across different pages.

In PHP, cookies are managed using the setcookie() function, and they are accessible through the $_COOKIE superglobal.


Setting Cookies in PHP

To create a cookie in PHP, you use the setcookie() function. This function must be called before any output is sent to the browser, including HTML or whitespace, because cookies are sent as HTTP headers.

The syntax for setting a cookie is:

setcookie(name, value, expiration, path, domain, secure, httponly);
  • name: The name of the cookie.
  • value: The value of the cookie.
  • expiration: The expiration time of the cookie (in seconds from the current time). If set to 0, the cookie will expire when the browser is closed.
  • path: The path on the server where the cookie is available. The default value is /, meaning the cookie is available across the entire website.
  • domain: The domain that the cookie is available to.
  • secure: If true, the cookie will only be sent over HTTPS connections.
  • httponly: If true, the cookie can only be accessed via HTTP(S) requests and not by JavaScript (enhancing security).

Here’s an example of setting a cookie:

<?php
setcookie('user', 'JohnDoe', time() + 3600, '/'); // Cookie expires in 1 hour
?>

This sets a cookie named user with the value JohnDoe that will expire in 1 hour.


Retrieving Cookies in PHP

Once a cookie has been set, you can retrieve its value using the $_COOKIE superglobal. The $_COOKIE array will hold all cookies sent with the current HTTP request.

For example, to retrieve the user cookie that we set earlier:

<?php
if (isset($_COOKIE['user'])) {
echo "Hello, " . $_COOKIE['user'];
} else {
echo "Cookie not found!";
}
?>

In this example, we check if the user cookie is set. If it is, we display its value; otherwise, we print a message saying that the cookie is not found.


Modifying and Unsetting Cookies

To modify a cookie, you can simply call the setcookie() function again with the same name but a different value. For example, to update the value of the user cookie:

<?php
setcookie('user', 'JaneDoe', time() + 3600, '/'); // Modify the cookie value
?>

If you want to delete a cookie, you can set its expiration time to a time in the past. This will instruct the browser to delete the cookie.

To delete a cookie:

<?php
setcookie('user', '', time() - 3600, '/'); // Expire the cookie
?>

Here, we set the cookie’s value to an empty string and its expiration time to one hour in the past, effectively deleting the cookie.


Cookie Expiration and Lifetime

The expiration time of a cookie is specified in seconds from the current time. For example, if you want a cookie to expire in 30 minutes, you can set the expiration time as follows:

setcookie('user', 'JohnDoe', time() + 1800, '/');  // Expires in 30 minutes

If you set the expiration time to 0, the cookie will expire when the browser is closed. This is useful for temporary cookies that should only persist during the session.

setcookie('session_cookie', 'value', 0, '/');  // Expires when the browser is closed

Secure Cookies and HttpOnly Cookies

Cookies can be made more secure by using the secure and httponly flags.

  • secure: If set to true, the cookie will only be sent over HTTPS connections, ensuring the cookie’s data is encrypted in transit.
  • httponly: If set to true, the cookie cannot be accessed via JavaScript, reducing the risk of cross-site scripting (XSS) attacks.

To set a secure and HttpOnly cookie:

setcookie('user', 'JohnDoe', time() + 3600, '/', '', true, true);  // Secure and HttpOnly

In this example:

  • The cookie will only be transmitted over HTTPS.
  • JavaScript will not be able to access the cookie, reducing the risk of XSS attacks.

Cookie Scope: Domain and Path

Cookies have a scope, meaning they are only accessible on certain pages and domains. The path and domain parameters allow you to control where the cookie is available.

  • path: The cookie will only be sent for requests that match the specified path. For example, if you set the path to /admin, the cookie will only be sent for requests to /admin/* and not for other pages.
setcookie('user', 'JohnDoe', time() + 3600, '/admin');  // Cookie is only available on /admin
  • domain: The cookie will be sent to all subdomains of the specified domain.
setcookie('user', 'JohnDoe', time() + 3600, '/', 'example.com');  // Available on all subdomains of example.com

If you don’t specify the domain parameter, the cookie will only be sent to the domain that set the cookie.


Practical Example: Remember Me Functionality

One of the most common uses for cookies is to implement “Remember Me” functionality on a website. This allows users to stay logged in between sessions.

Login Form (login.php)

<form method="POST" action="login_process.php">
<label for="username">Username:</label>
<input type="text" name="username" required>
<label for="password">Password:</label>
<input type="password" name="password" required>
<label for="remember_me">
<input type="checkbox" name="remember_me"> Remember Me
</label>
<input type="submit" value="Login">
</form>

Login Processing (login_process.php)

<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$remember_me = isset($_POST['remember_me']) ? true : false;

// Validate credentials (this is just a simple example)
if ($username == 'John' && $password == 'password123') {
$_SESSION['username'] = $username;

// Set a cookie if "Remember Me" is checked
if ($remember_me) {
setcookie('username', $username, time() + 3600 * 24 * 30, '/'); // Expires in 30 days
}

header("Location: welcome.php");
exit();
} else {
echo "Invalid credentials!";
}
?>

Welcome Page (welcome.php)

<?php
session_start();

if (isset($_SESSION['username'])) {
echo "Welcome, " . $_SESSION['username'];
} elseif (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'] . " (via cookie)";
} else {
echo "Please log in.";
}
?>

In this example, if the “Remember Me” checkbox is checked, the username is stored in a cookie that lasts for 30 days. On subsequent visits, the username will be retrieved from the cookie, allowing the user to be automatically logged in.


Troubleshooting Common Cookie Issues

  1. Cookies Not Being Set: Make sure that you call setcookie() before any HTML output. Cookies are sent as HTTP headers, so they must be set before the content is sent to the browser.
  2. Cookies Not Persisting: If your cookies are not persisting, ensure that the expiration time is set correctly. If the expiration time is set to 0, the cookie will expire when the browser is closed.
  3. Session Cookies Not Working: Session cookies will only persist until the browser is closed. If you’re trying to test cookies and the session is expired, ensure you haven’t set an immediate expiration time.
  4. Domain and Path Issues: Make sure that the domain and path are set correctly. If you’re using subdomains or specific directories, ensure that the cookie is accessible in those areas.

Summary

In this module, we explored cookies in PHP and how they are used to store data on the client side. We discussed how to set, retrieve, modify, and delete cookies using PHP’s setcookie() function and the $_COOKIE superglobal. We also covered topics such as cookie expiration, secure cookies, and scope (domain and path). Finally, we provided a practical example of implementing “Remember Me” functionality with cookies.