How to Use Sessions and Cookies in PHP

When building a web application, we often need to remember user information across pages — for example, login status, display preferences, or the contents of a shopping cart. HTTP...

How to Use Sessions and Cookies in PHP
Advertisement

When building a web application, we often need to remember user information across pages — for example, login status, display preferences, or the contents of a shopping cart. HTTP itself is stateless (it doesn't remember state), so PHP provides two mechanisms to handle this: Session and Cookie. Each has different characteristics and suits different use cases.

The Difference Between Sessions and Cookies

  • Session — data is stored on the server. The browser only keeps a session ID (a small cookie). Safer for sensitive data such as login status.
  • Cookie — data is stored directly in the user's browser. It can be accessed and manipulated by the user. Suitable for non-sensitive data such as theme preferences or a remembered username.

Using Sessions in PHP

To use a session, call session_start() at the beginning of every page that needs the session, before any HTML output:

<?php
session_start();

// Storing data in the session
$_SESSION['user_id']   = 42;
$_SESSION['username']  = 'budi_santoso';
$_SESSION['is_logged_in'] = true;

echo "Session created successfully for: " . $_SESSION['username'];

Reading the session on another page:

Advertisement
<?php
session_start();

if (isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] === true) {
    echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!";
} else {
    header('Location: login.php');
    exit;
}

Example: A Login System with Sessions

Here's a simple example of a login process that stores data in the session:

<?php
// login.php
session_start();
require 'connection.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username LIMIT 1");
    $stmt->execute([':username' => $username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        // Regenerate the session ID after login — important for security!
        session_regenerate_id(true);

        $_SESSION['user_id']      = $user['id'];
        $_SESSION['username']     = $user['username'];
        $_SESSION['is_logged_in'] = true;

        header('Location: dashboard.php');
        exit;
    } else {
        $error = "Incorrect username or password.";
    }
}

Destroying a Session (Logout)

For a clean logout, remove all session data and destroy the session:

<?php
// logout.php
session_start();

// Remove all session variables
$_SESSION = [];

// Remove the session cookie from the browser
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Destroy the session on the server
session_destroy();

header('Location: login.php');
exit;

Using Cookies in PHP

Cookies are created with the setcookie() function, which must be called before any HTML output:

<?php
// Create a cookie that lasts 30 days
$expire = time() + (30 * 24 * 60 * 60); // 30 days in seconds

setcookie(
    'favorite_theme', // cookie name
    'dark',           // value
    [
        'expires'  => $expire,
        'path'     => '/',
        'secure'   => true,   // only send over HTTPS
        'httponly' => true,   // not accessible from JavaScript
        'samesite' => 'Lax',  // basic CSRF protection
    ]
);

echo "Theme cookie saved successfully!";

Reading and deleting a cookie:

Advertisement
<?php
// Reading a cookie
if (isset($_COOKIE['favorite_theme'])) {
    $theme = $_COOKIE['favorite_theme'];
    echo "Your chosen theme: " . htmlspecialchars($theme);
}

// Delete a cookie by setting its expiration time to the past
setcookie('favorite_theme', '', time() - 3600, '/');
echo "Cookie has been deleted.";

Session and Cookie Security Tips

  • Always call session_regenerate_id(true) after a successful login to prevent a session fixation attack.
  • Set httponly = true on cookies so they can't be accessed from JavaScript (protecting against XSS).
  • Set secure = true so cookies are only sent over HTTPS.
  • Don't store sensitive data (such as passwords) in exposed cookies or sessions.
  • Set a reasonable session timeout in php.ini: session.gc_maxlifetime.

Conclusion

Sessions and cookies are the two main tools for managing user state in PHP. Use sessions for sensitive data such as login status, and cookies for preferences the browser is allowed to remember. By applying the right security practices — such as regenerating the session ID and using secure cookie attributes — your application will be far more protected against common attacks like session hijacking and XSS.

Advertisement
session php cookie php php session login cara pakai session php perbedaan session dan cookie php php native session
Share this article
Back to Blog
🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →
Advertisement
Latest Articles
Oct 15, 2026
Oct 14, 2026
Oct 13, 2026
Oct 11, 2026
Advertisement