Sessions and cookies are essential for maintaining state and storing data across multiple pages or visits in PHP applications.

Starting a Session

Sessions allow you to store user data across multiple pages. To start a session, use the session_start() function.

  • Starting a Session:
  <?php
session_start(); // Must be called at the beginning of the script
?>
  

Session Variables

Session variables are used to store data that you want to persist across different pages during a user’s visit.

  • Setting Session Variables:
  <?php
session_start();
$_SESSION['username'] = 'JohnDoe';
?>
  
  • Accessing Session Variables:
  <?php
session_start();
echo $_SESSION['username']; // Outputs: JohnDoe
?>
  
  • Unsetting Session Variables:
  <?php
session_start();
unset($_SESSION['username']);
?>
  
  • Destroying a Session:
  <?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>
  

Managing Sessions

Sessions can be configured and managed through PHP’s php.ini settings or programmatically.

  • Configuring Session Settings:

    • session.gc_maxlifetime - Maximum lifetime of session data in seconds.
    • session.save_path - Directory where session files are stored.
  • Custom Session Handlers:

  • You can implement custom session handling mechanisms using session_set_save_handler().

Working with Cookies

Cookies are small pieces of data stored on the client’s browser. They can be used to remember user preferences or session data.

  • Setting Cookies:
  <?php
setcookie('user', 'JohnDoe', time() + 3600); // Expires in 1 hour
?>
  
  • Accessing Cookies:
  <?php
echo $_COOKIE['user']; // Outputs: JohnDoe
?>
  
  • Deleting Cookies:
  <?php
setcookie('user', '', time() - 3600); // Expired in the past
?>
  
  • Cookie Attributes:

    • Expiration Time: Set with the third parameter of setcookie().
    • Path: The path on the server where the cookie will be available.
    • Domain: The domain where the cookie is valid.
    • Secure: Indicates if the cookie should only be sent over secure connections.
    • HttpOnly: Makes the cookie accessible only through the HTTP protocol.

Sessions and cookies are fundamental for managing user state and preferences in web applications. Proper implementation ensures that user data is handled securely and efficiently.