Basic
Advanced
Examples
PHP 8 - Sessions and Cookies
Last modified: April 02, 20221. Cookies
Create a cookie
setcookie("name", "kafle", time()+ 30,'/'); // expires after 30 seconds
Modify the cookie
setcookie("name", "resham", time()+ 30,'/'); // expires after 30 seconds
Read the cookie
echo "My name is : ". $_COOKIE["resham"]
Delete a cookie
setcookie("name", "", time() - 3600); // expires after 30 seconds
2. Sessions
Session is used to store variable across multiple web page. It hold data for a single user.
A session is started with the session_start() function.
Create a session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["name"] = "kafle"; //session nae is name and hold kafle data
?>
</body>
</html>
Modify the session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["name"] = "resham"; //session nae is name and hold resham data
?>
</body>
</html>
Delete a session
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
unset($_SESSION['name']);?>
</body>
</html>
Delete ALL sessions
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>