Welcome back to our PHP tutorial series! Managing user state and data across different pages is a common task in web development. PHP provides two powerful mechanisms to handle this: cookies and sessions. In this article, we’ll explore how to use cookies and sessions in PHP to store and manage user data. Let’s dive in!
Cookies in PHP
Cookies are small pieces of data stored on the client’s browser. They are often used to remember user preferences, track user sessions, or store small amounts of data between visits.
Setting a Cookie
You can set a cookie using the setcookie()
function. This function must be called before any output is sent to the browser.
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
// Set a cookie that expires in 30 days
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cookie</title>
</head>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Getting a Cookie
You can access a cookie value using the $_COOKIE
superglobal array.
Example
<?php
if (isset($_COOKIE["user"])) {
echo "User is " . $_COOKIE["user"];
} else {
echo "User is not set";
}
?>
Deleting a Cookie
To delete a cookie, set its expiration date to a time in the past.
Example
<?php
// Delete the cookie
setcookie("user", "", time() - 3600, "/");
?>
Sessions in PHP
Sessions are used to store data on the server for individual users against a unique session ID. Unlike cookies, session data is not stored on the client’s browser.
Starting a Session
To start a session, use the session_start()
function. This function must be called at the beginning of the script before any output is sent to the browser.
Example
<?php
// Start the session
session_start();
?>
Setting Session Variables
You can store data in session variables using the $_SESSION
superglobal array.
Example
<?php
session_start();
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john.doe@example.com";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Session</title>
</head>
<body>
<?php
echo "Session variables are set.";
?>
</body>
</html>
Getting Session Variables
You can access session variables using the $_SESSION
superglobal array.
Example
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Username is " . $_SESSION["username"];
} else {
echo "Username is not set";
}
?>
Unsetting and Destroying Sessions
To remove specific session variables, use the unset()
function. To destroy all session data, use the session_destroy()
function.
Example
<?php
session_start();
// Remove a specific session variable
unset($_SESSION["username"]);
// Destroy all session data
session_destroy();
?>
Example: Login System with Sessions
Let’s create a simple login system using sessions.
HTML Form (login.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
PHP Script (login.php)
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
// Simple username and password check
if ($username == "admin" && $password == "password") {
$_SESSION["username"] = $username;
header("Location: welcome.php");
} else {
echo "Invalid username or password";
}
?>
Welcome Page (welcome.php)
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: login.html");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h2>Welcome, <?php echo $_SESSION["username"]; ?>!</h2>
<a href="logout.php">Logout</a>
</body>
</html>
Logout Script (logout.php)
<?php
session_start();
session_destroy();
header("Location: login.html");
exit();
?>
Conclusion
Handling cookies and sessions in PHP allows you to manage user data and state effectively. Cookies are stored on the client-side and are useful for storing small pieces of data, while sessions store data on the server-side and provide a more secure way to manage user information.
In our next article, we’ll explore more advanced topics in PHP. Stay tuned and happy coding!
As always, if you have any questions or need further clarification, feel free to leave a comment below. We’re here to help you on your PHP journey!