This tutorial aims to provide a detailed guide on how to implement secure sessions and cookies in PHP. By the end of this tutorial, you will be able to:
Prerequisites:
This tutorial assumes you have basic knowledge of PHP and the concept of HTTP and HTTPS.
Sessions and cookies are both used to preserve state information between page requests. Cookies are small files stored on the client’s computer, whereas sessions are server-side files that correspond to a particular user. A session ID is stored in the user's browser, which is used to fetch session data from the server.
To create a secure session in PHP, you should always start your script with session_start()
. This tells PHP to create a new session or resume the current one.
To make your sessions more secure, you should:
session_regenerate_id()
whenever the security level changes.Cookies should always be sent over HTTPS to prevent interception and protect sensitive data. In PHP, you can set the secure flag when setting a cookie using setcookie()
.
<?php
// Start the session
session_start();
// Regenerate session ID
session_regenerate_id();
// Store session data
$_SESSION["userid"] = "user123";
?>
In the above example, session_start()
starts a new session or resumes the current one. session_regenerate_id()
generates a new session ID to prevent session fixation attacks. We then store the user ID in the session data.
<?php
// Set a secure cookie
setcookie("cookie_name", "cookie_value", [
'expires' => time() + 3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true, // this means the cookie will only be set if a secure connection exists.
'httponly' => true // this means the cookie can only be accessed via HTTP(S) not by scripting languages
]);
?>
In the above example, setcookie()
sets a secure cookie that can only be sent over HTTPS and cannot be accessed by scripting languages.
In this tutorial, we have covered how to implement secure sessions and cookies in PHP. We have learned how to create a session, regenerate session ID, store session data, and set a secure cookie.
For further learning, consider understanding how to use cookies for authentication and how to handle session expiration.
Exercise 1: Create a session, store user data into it, and then retrieve the data.
Solution:
<?php
// Start the session
session_start();
// Store data
$_SESSION["username"] = "John Doe";
// Retrieve data
echo $_SESSION["username"];
?>
Exercise 2: Set a secure cookie with a specific expiration time and then retrieve its value.
Solution:
<?php
// Set a secure cookie
setcookie("TestCookie", "TestValue", [
'expires' => time() + 3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true
]);
// Retrieve cookie value
if(isset($_COOKIE["TestCookie"])) {
echo $_COOKIE["TestCookie"];
}
?>
Continue practicing by creating sessions and cookies with different parameters and options.