Sessions and Cookies in PHP - Codingque

Sessions and Cookies in PHP

Learn how to manage user data across multiple pages using sessions and cookies in PHP. Understand best practices for session security.

Working with Sessions

PHP sessions allow you to store and manage user data across multiple pages. Unlike cookies, session data is stored on the server and is more secure.

Starting a Session

To start a session, use the session_start() function at the beginning of your PHP script. This function initializes a session or resumes the current one based on a session identifier passed via a request.

<?php
session_start();
?>

Storing Session Data

Use the $_SESSION superglobal array to store session data. This array holds the session variables and is accessible on any page after the session is started.

<?php
session_start();
$_SESSION['username'] = 'JohnDoe';
?>

Retrieving Session Data

You can retrieve session data on another page by accessing the $_SESSION array.

<?php
session_start();
echo 'Welcome, ' . $_SESSION['username'];
?>

Destroying a Session

To end a session and clear all session data, use the session_destroy() function.

<?php
session_start();
session_destroy();
?>

Working with Cookies

Cookies are small pieces of data stored on the client's browser. They are often used to store user preferences or session information.

Setting a Cookie

Use the setcookie() function to create a cookie. The function takes several parameters, including the name, value, expiration time, and path of the cookie.

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

Retrieving a Cookie

Access the value of a cookie using the $_COOKIE superglobal array.

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

Session Security Best Practices

Regenerate Session ID

Use session_regenerate_id() to regenerate the session ID periodically, reducing the risk of session fixation attacks.

<?php
session_start();
session_regenerate_id(true);
?>

Set Session Cookie Parameters

Configure session cookies to be HTTP-only and secure by using session_set_cookie_params().

<?php
session_set_cookie_params([
    'lifetime' => 86400,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
]);
session_start();
?>

Session Timeout

Implement session timeouts to automatically log out users after a period of inactivity.

<?php
session_start();
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
    session_unset();
    session_destroy();
}
$_SESSION['last_activity'] = time();
?>
Previous Next
Modern Footer