Session Management

PHP supports sessions and cookies, which allow you to store user information to be used across multiple pages. This is a fundamental part of creating interactive and personalized web applications.

Cookies

A cookie is a small file that the server embeds on the user's computer. PHP can create and retrieve cookie values. Here's how you can set a cookie in PHP:

<?php
setcookie("user", "Alex Porter", time() + (86400 * 30), "/"); // 86400 = 1 day
?>

And this is how you can retrieve a cookie value:

<?php
if(!isset($_COOKIE["user"])) {
  echo "Cookie named 'user' is not set!";
} else {
  echo "Cookie 'user' is set!<br>";
  echo "Value is: " . $_COOKIE["user"];
}
?>

Sessions

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the user's computer. Here's how you can start a session and set session variables:

<?php
session_start();

$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

To retrieve session data, just reference the session variable as you would any other variable:

<?php
session_start();
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

Sessions and cookies are important for maintaining user data across multiple pages, and enable the creation of more complex, personalized web applications.

Session Hijacking

Session Hijacking, also known as cookie hijacking, is the exploitation of a valid computer session to gain unauthorized access to information or services in a computer system. In particular, it is used to refer to the theft of a magic cookie used to authenticate a user to a remote server.

PHP session hijacking can be mitigated by regenerating session ID after login. This is because if a session ID is compromised before login, a new session ID is assigned to the user upon login, making the compromised session ID useless.

Here is an example of how you can regenerate a session ID upon user login in PHP:

<?php
session_start();
if ($_POST['username'] === 'admin' && $_POST['password'] === 'password') { // Check user's credentials (This is just an example, real world applications require much more secure methods)
    // Regenerate session ID upon successful login
    session_regenerate_id();
    $_SESSION['logged_in'] = true;
    echo "Logged in successfully!";
} else {
    echo "Invalid login credentials!";
}
?>

In the above example, session_regenerate_id() function regenerates the session ID each time a user logs in, which can help to prevent session hijacking.

Note: this is just one of the methods to prevent session hijacking, and usually it is used in combination with other security measures.

Last updated