PHP Sessions and cookies


Sessions and cookies are two mechanisms used in PHP to manage state and store information across multiple requests by the same user. They are essential for maintaining user data, preferences, and authentication status in web applications.

Sessions in PHP

Sessions are used to store user data on the server side. They allow you to maintain state across multiple requests from the same user.

1. Starting a Session

To use sessions, you must start a session at the beginning of your script using the session_start() function. This function either creates a new session or resumes the existing one.

Example:

<?php session_start(); // Start the session $_SESSION['username'] = 'JohnDoe'; // Store data in the session ?>

2. Storing and Retrieving Data

Data stored in a session is accessible across different pages during the same session.

Storing Data:

<?php session_start(); $_SESSION['user_id'] = 12345; // Store a user's ID ?>

Retrieving Data:

<?php session_start(); echo $_SESSION['user_id']; // Outputs: 12345 ?>

3. Destroying a Session

To clear all session data and destroy the session, use session_destroy(). It’s often combined with session_unset() to remove all session variables.

Example:

<?php session_start(); session_unset(); // Remove all session variables session_destroy(); // Destroy the session ?>

4. Session Configuration

You can configure session settings in the php.ini file or use session_set_cookie_params() to set cookie parameters for sessions.

Example:

<?php session_start(); session_set_cookie_params([ 'lifetime' => 86400, // Cookie lifetime in seconds 'path' => '/', 'domain' => 'example.com', 'secure' => true, // Use HTTPS 'httponly' => true // Accessible only via HTTP, not JavaScript ]); ?>

Cookies in PHP

Cookies are used to store data on the client side (in the user's browser). Cookies can store small amounts of data and are sent with every HTTP request to the server.

1. Setting a Cookie

Use the setcookie() function to create a cookie. This function must be called before any output is sent to the browser.

Example:

<?php // Set a cookie with a name, value, and expiration time setcookie('user', 'JohnDoe', time() + 3600, '/'); // Expires in 1 hour ?>

2. Retrieving a Cookie

Cookies are accessible via the $_COOKIE superglobal array.

Example:

<?php if (isset($_COOKIE['user'])) { echo $_COOKIE['user']; // Outputs: JohnDoe } else { echo 'Cookie not set'; } ?>

3. Deleting a Cookie

To delete a cookie, set its expiration date to a past time.

Example:

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

4. Cookie Parameters

When setting cookies, you can configure various parameters such as lifetime, path, domain, secure, and HTTP-only.

Example:

<?php setcookie('user', 'JohnDoe', [ 'expires' => time() + 3600, // Expiration time 'path' => '/', // Cookie path 'domain' => 'example.com', // Cookie domain 'secure' => true, // Use HTTPS 'httponly' => true // Accessible only via HTTP, not JavaScript ]); ?>

Differences Between Sessions and Cookies

  1. Storage Location:

    • Sessions: Store data on the server.
    • Cookies: Store data on the client’s browser.
  2. Data Security:

    • Sessions: More secure as data is stored on the server.
    • Cookies: Less secure as data is stored on the client and can be manipulated.
  3. Data Size:

    • Sessions: Can store larger amounts of data.
    • Cookies: Limited to about 4KB of data.
  4. Persistence:

    • Sessions: Exist only until the session ends (e.g., when the browser is closed or the session is explicitly destroyed).
    • Cookies: Can persist across sessions based on the expiration time set.

Best Practices

  1. For Sessions:

    • Use session_start() at the beginning of scripts that require session access.
    • Store minimal and non-sensitive data in sessions.
    • Use secure session handling settings.
  2. For Cookies:

    • Set appropriate expiration times and use secure flags (e.g., secure, httponly).
    • Avoid storing sensitive information in cookies.
    • Regularly check and clean up expired or unused cookies.