Working with Cookies and Session Handlers

What are Cookies and Sessions?

Cookies and sessions are mechanisms for storing data on the client-side and server-side, respectively. They are essential for maintaining state in web applications, especially in stateless HTTP protocols.

  • Cookies: Small pieces of data stored on the client’s browser. They can persist for a defined period, making them suitable for remembering user preferences or tracking users.
  • Sessions: Server-side storage of data for a particular user session. Sessions store data temporarily and are deleted when the user closes the browser or after a specified time.

Working with Cookies

To create a cookie in PHP, use the setcookie() function. The syntax is as follows:

    <?php
    setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // 86400 = 1 day
    ?>
                

Example: Setting a Cookie

This example sets a cookie named username that expires in 30 days:

    <?php
    setcookie("username", "JohnDoe", time() + (86400 * 30), "/");
    echo "Cookie named 'username' is set! Value is: " . $_COOKIE["username"];
    ?>
                

Expected Output

Cookie named 'username' is set! Value is: JohnDoe

Accessing Cookies

To access a cookie, use the $_COOKIE superglobal array:

    <?php
    if(isset($_COOKIE["username"])) {
        echo "Welcome " . $_COOKIE["username"];
    } else {
        echo "Welcome Guest";
    }
    ?>
                

Expected Output

If the cookie is set, it will display: Welcome JohnDoe
If not set, it will display: Welcome Guest

Working with Sessions

To start a session in PHP, use the session_start() function. You can store session variables using the $_SESSION superglobal:

    <?php
    session_start(); // Start the session
    $_SESSION["username"] = "JohnDoe";
    ?>
                

Example: Setting a Session Variable

This example starts a session and sets a session variable:

    <?php
    session_start();
    $_SESSION["username"] = "JohnDoe";
    echo "Session variable 'username' is set! Value is: " . $_SESSION["username"];
    ?>
                

Expected Output

Session variable 'username' is set! Value is: JohnDoe

Accessing Session Variables

To access session variables, use the $_SESSION superglobal:

    <?php
    session_start();
    if(isset($_SESSION["username"])) {
        echo "Welcome back " . $_SESSION["username"];
    } else {
        echo "Welcome Guest";
    }
    ?>
                

Expected Output

If the session variable is set, it will display: Welcome back JohnDoe
If not set, it will display: Welcome Guest

Summary

Cookies and sessions are fundamental to maintaining user state in web applications. Use cookies for persistent data that can be accessed on the client side and sessions for temporary data stored on the server. Always be cautious about security, especially when handling sensitive information.