How to use PHP Session & PHP Cookies with Example

Last updated on : Jun 17, 2023 by Ashwini Upadhyay

In this tutorial, we are going to learn about PHP sessions and PHP cookies with examples. In PHP, a session is a way of preserving data across multiple requests made by the same user, let’s now take a closer look at cookies and see how they differ from sessions.

PHP Session

Sessions in PHP are a way of temporarily storing and making data accessible across all website pages. This will create a temporary file that stores various session variables and their values. It will be destroyed when you close the website. This file is then available on all pages of the website for the user to access information about.

✤ Here is a simple example of using sessions in PHP:

// Start a new session or resume an existing one
session_start();

// Set session variables
$_SESSION['username'] = 'Hero';
$_SESSION['email'] = 'hero@example.com';

// Accessing session variables
echo 'Username: ' . $_SESSION['username'] . '<br>';
echo 'Email: ' . $_SESSION['email'] . '<br>';

// Destroying the session
session_destroy();

✤ Here is an example of a user login system using PHP sessions:

Step 1: login.php (for login form):

As you can see In this example, the login.php file displays a login form where you can enter your username and password. it checks if the provided credentials are valid (in this case, a hardcoded username and password for simplicity). If the login is successful, it sets the username value in the session and redirects you to the dashboard.php page.

<?php
session_start();

// Check if the user is already logged in
if (isset($_SESSION['username'])) {
    header("Location: dashboard.php");
    exit();
}

// Check if the login form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate the username and password (you should perform proper validation and authentication)
    if ($username === 'hero' && $password === 'password123') {
        // Set the username in the session
        $_SESSION['username'] = $username;

        // Redirect to the dashboard
        header("Location: dashboard.php");
        exit();
    } else {
        $error = "Invalid username or password";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <?php if (isset($error)) {
        echo "<p>$error</p>";
    } ?>
    <form method="POST" action="login.php">
        <input type="text" name="username" placeholder="Username"><br>
        <input type="password" name="password" placeholder="Password"><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

Step 2: dashboard.php (for authenticated dashboard):

The dashboard.php file checks if you are logged in by verifying if the username session variable is set. If not, it redirects the user back to the login page. Otherwise, it displays a welcome message along with the authenticated dashboard content.

<?php
session_start();

// Check if the user is not logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

$username = $_SESSION['username'];
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h2>Welcome, <?php echo $username; ?></h2>
    <p>This is your dashboard.</p>
    <a href="logout.php">Logout</a>
</body>
</html>

Step 3: logout.php (to log out the user):

The logout.php file clears the session data by unsetting all session variables and destroying the session. It then redirects the user back to the login page.

<?php
session_start();

// Clear the session data
session_unset();
session_destroy();

// Redirect to the login page
header("Location: login.php");
exit();
?>

Remember, this example is for educational purposes and doesn’t cover advanced security measures. In a real-world scenario, you would implement proper validation, password hashing, and other security practices.

PHP Cookies

In PHP, cookies are a mechanism for storing small amounts of data on a user’s browser. They are commonly used to remember user preferences, track user activities, and facilitate personalized experiences on websites.

PHP provides functions and superglobal variables for working with cookies:

setcookie() function: This function is used to create or modify a cookie. It takes parameters such as cookie name, value, expiration time, path, and domain.

Here’s an example that demonstrates setting a cookie with different parameters:

// Set a cookie with all parameters
setcookie(
    'username',        // Name
    'JohnDoe',         // Value
    time() + 3600,     // Expiration time (1 hour from now)
    '/',               // Path (valid for the entire domain)
    '.example.com',    // Domain (valid for all subdomains of example.com)
    true,              // Secure (transmitted over HTTPS)
    true               // HttpOnly (not accessible by client-side scripts)
);

$_COOKIE superglobal array: This is an associative array that holds the values ​​of cookies sent by the user’s browser. You can access cookie values ​​by using their names as array keys, such as $_COOKIE['cookie_name'].

✤ Here’s an example of setting and retrieving a cookie in PHP:

// Set a cookie
setcookie('username', 'JohnDoe', time() + 3600); // Expires in 1 hour

// Accessing the cookie value
if (isset($_COOKIE['username'])) {
    echo 'Username: ' . $_COOKIE['username'] . '<br>';
} else {
    echo 'Cookie not set.';
}

✤ Here’s an example of unset or deleting a cookie in PHP

unset or delete a cookie in PHP, you can use the setcookie() function with an expiration time in the past. This effectively removes the cookie from the client’s browser. As you can see in this example:

// Set the cookie expiration time to a past date
$cookie_name = 'username';
$cookie_value = ''; // Empty value
$expiration_time = time() - 3600; // Set the expiration time to one hour ago

// Set the cookie with an expiration time in the past
setcookie($cookie_name, $cookie_value, $expiration_time);

// Unset the cookie from the $_COOKIE superglobal
unset($_COOKIE[$cookie_name]);

In the code above example, replace ‘your_cookie_name’ with the name of the cookie you want to unset. By setting the expiration time to a past date, the cookie will be invalidated and removed from the browser.

Conclusion

In short, sessions are stored on the server-side, while cookies are stored on the client-side. Sessions are typically used to store large amounts of user-specific data, while cookies are typically used for smaller preferences or tracking purposes.

ashwini upadhyay

Ashwini Upadhyay

I'm a full-stack developer, owner of LogicalDuniya.I love to write tutorials and tips that can help to other artisan. I love to write on PHP, Laravel, Angular, Vue, React, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

Recommended Posts :


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Press ESC to close