Lesson 9: PHP Sessions and Cookies

In this lesson, we will explore how to manage state in PHP using cookies and sessions. These tools allow you to store data about users and their interactions with your website, providing the foundation for features like user authentication, shopping carts, and preferences.


9.1 Setting and Retrieving Cookies

What are Cookies?

  • Definition: Small pieces of data stored on the client’s browser.
  • Purpose: Track user activity, preferences, or login sessions.
  • Lifetime: Cookies can persist for a set duration or until the browser is closed.

Setting Cookies

Use the setcookie() function to create cookies.

  • Syntax:
    php
    setcookie(name, value, expire, path, domain, secure, httponly);
    • name: Name of the cookie.
    • value: Value to be stored.
    • expire: Expiration time in UNIX timestamp format.
    • path: Path where the cookie is accessible.
    • domain: Domain where the cookie is valid.
    • secure: Whether to transmit over HTTPS only.
    • httponly: Restrict cookie access to HTTP(S) protocols only.

Example: Setting a Cookie

php
<?php
// Set a cookie that expires in 1 hour
setcookie("username", "JohnDoe", time() + 3600);
echo "Cookie has been set.";
?>

Retrieving Cookies

Access cookies using the $_COOKIE superglobal.

php
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Hello, guest!";
}
?>

Example: Deleting a Cookie

  • Set the expiration time to a past date.
php
<?php
setcookie("username", "", time() - 3600);
echo "Cookie has been deleted.";
?>

9.2 Working with Sessions

What are Sessions?

  • Definition: Sessions store data on the server for a user during their visit.
  • Purpose: Keep track of user data across multiple pages (e.g., shopping cart, login state).
  • Lifetime: Active until the user closes the browser or the session times out.

Starting a Session

  • Use the session_start() function at the beginning of your script to initialize a session.
  • Syntax:
    php
    session_start();

Storing Session Data

  • Store data in the $_SESSION superglobal array.
php
<?php
session_start();
$_SESSION["username"] = "JohnDoe";
echo "Session has been set.";
?>

Accessing Session Data

  • Access session variables using the $_SESSION array.
php
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome, " . $_SESSION["username"];
} else {
echo "Session not set.";
}
?>

Destroying a Session

  • Use session_unset() to clear session variables and session_destroy() to terminate the session.
php
<?php
session_start();
session_unset(); // Clears all session variables
session_destroy(); // Destroys the session
echo "Session has been destroyed.";
?>

Comparison of Cookies and Sessions

Feature Cookies Sessions
Storage Client-side Server-side
Security Less secure (stored in the browser) More secure (stored on the server)
Data Size Limited (4KB per cookie) Unlimited (depends on server memory)
Lifetime Can persist after browser is closed Ends when browser is closed or timed out
Use Cases Remember user preferences or login state Shopping carts, user authentication

Practical Examples

Example 1: Login System with Sessions

  1. Login Form:
    php
    <form method="POST" action="login.php">
    Username: <input type="text" name="username"><br>
    <input type="submit" value="Login">
    </form>
  2. Processing Login:
    php
    <?php
    session_start();
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION["username"] = $_POST["username"];
    echo "Welcome, " . $_SESSION["username"];
    }
    ?>
  3. Displaying User Data:
    php
    <?php
    session_start();
    if (isset($_SESSION["username"])) {
    echo "Hello, " . $_SESSION["username"];
    } else {
    echo "Please log in.";
    }
    ?>
  4. Logout:
    php
    <?php
    session_start();
    session_unset();
    session_destroy();
    echo "You have logged out.";
    ?>

Example 2: Remember Me with Cookies

  1. Login Form:
    php
    <form method="POST" action="remember_me.php">
    Username: <input type="text" name="username"><br>
    <input type="checkbox" name="remember" value="1"> Remember Me<br>
    <input type="submit" value="Login">
    </form>
  2. Processing Login:
    php
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    if (isset($_POST["remember"])) {
    setcookie("username", $username, time() + 3600); // Cookie valid for 1 hour
    }
    echo "Welcome, $username";
    }
    ?>
  3. Displaying User Data:
    php
    <?php
    if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . $_COOKIE["username"];
    } else {
    echo "Please log in.";
    }
    ?>

Activities and Exercises

  1. Cookies:
    • Create a script to set a cookie for the user’s preferred language. Display a greeting in that language on subsequent visits.
  2. Sessions:
    • Build a shopping cart system using sessions where users can add, view, and clear items.
  3. Combination:
    • Create a login system that uses sessions for authentication and cookies for remembering the username.

Assignment

  1. Part 1: Using Cookies
    • Create a form where users can input their favorite color.
    • Save the color in a cookie and display the page’s background in that color when revisited.
  2. Part 2: Using Sessions
    • Create a multi-page application:
      1. A form on Page 1 collects the user’s name.
      2. Page 2 displays a personalized greeting using session data.
      3. A logout button on Page 3 clears the session.

Summary

In this lesson, you learned how to:

  1. Set, retrieve, and delete cookies in PHP.
  2. Work with sessions to manage user data across multiple pages.
  3. Understand the differences and use cases for cookies and sessions.

These skills are essential for creating dynamic, user-focused web applications. Let me know if you’d like additional examples or exercises!

You said:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *