Hello, aspiring PHP developers!
In the world of web development, retaining user-specific data across multiple pages is a recurring requirement. Whether it’s to remember user preferences, keep a user logged in, or track a user’s activities on a website, sessions and cookies come to the rescue.
Today, we will introduce you to the fundamental concepts of sessions and cookies in PHP and show you how to utilize them effectively.
Sessions vs. Cookies
Before we dive in, let’s understand the basic difference:
Sessions store user information on the server for a limited duration. This means the data isn’t accessible after the session expires or is destroyed.
Cookies store user information on the user’s computer in text files. They can keep data for extended durations until the cookie’s expiration time is reached or it’s manually deleted.
PHP Sessions
- Starting a Session: To start a session in PHP, use the session_start() function at the beginning of your script
session_start();
- Storing Session Data: You can save data into the session array for later use
$_SESSION["username"] = "JDoodle";
- Retrieving Session Data: To fetch data stored in a session
echo "Hello, " . $_SESSION["username"];
- Destroying a Session: To end a session and erase session data
session_unset(); // remove all session variables
session_destroy(); // destroy the session
PHP Cookies
- Setting Cookies: To create a cookie in PHP
setcookie("user", "JDoodle", time() + 3600, "/"); // cookie will expire after 1 hour
- Retrieving Cookie Values: To fetch a cookie’s value:
echo "User: " . $_COOKIE["user"];
- Deleting a Cookie: To delete a cookie, just set its expiration time to a past timestamp
setcookie("user", "", time() - 3600, "/");
Exercise
It’s practice time!
- Build a basic login form with fields for a username and password.
- When a user submits the form, start a session and store the username in it.
- On subsequent pages, check if the session variable for the username exists to determine if the user is logged in.
- Provide a logout option that destroys the session and redirects the user to the login page.
Conclusion
Sessions and cookies empower developers to craft more personalized and secure web experiences. As you delve deeper into web development, mastering these concepts will be crucial.
So keep experimenting, keep refining, and enjoy your journey in the vast realm of PHP!
