To correctly complete request and response activities, web pages must temporarily or permanently store data. Almost every web development language has sessions and cookies to store client and server information, delivering a seamless and secure experience. This article will go over PHP sessions and cookies in detail.
What are cookies and sessions?
Cookies are little files that are saved on the client’s computer and can include information about the user, the request, the answer, and the server. They are delivered to the server alongside requests, letting the server to identify the user. A user can also build their own cookies and store data in them for later access. A session is an object that stores data related to a specific visitor throughout their visits, including login information, account details, and other form entries.
How to create a cookie in PHP
PHP’s setcookie()
method is used to create a new cookie. The general syntax for creating a cookie in PHP is as follows:
setcookie(name, value, expire, path, domain, secure, httponly);
The first parameter, name
, is the only required one. The rest of the parameters are optional. Here is an example of creating a cookie:
setcookie("my_first_cookie","It contains a string");
How to retrieve cookies and their value?
PHP stores cookies in the $_COOKIE global variable. To obtain a cookie and its value, simply provide the cookie’s name to the global variable. Here’s an example of utilizing the global variable to acquire a cookie:
$_COOKIE["my_first_cookie"] // will return "It contains a string"
How to delete cookies?
A cookie can be configured to expire after a certain period of time, after which it will be immediately destroyed. Here’s an example of generating a cookie with a one-day expiration time:
setcookie("my_first_cookie","It contains a string", time() + (86400), "/"); // 86400 = 1 day
Because the cookie’s expiration period must be in seconds, we used the time() method to return the current time and add the amount of seconds in a day (86400).
How to update cookies?
The same setcookie() function may be used to update a cookie. Simply invoke the function with the cookie’s name and set the new arguments. Here’s an example of changing the expiry period of a cookie to two days:
setcookie("my_first_cookie","It contains a string", time() + (86400 * 2), "/"); // 86400 = 1 day
It’s worth mentioning that cookies are automatically URL encoded when submitted in a request and decoded when received. The setrawcookie() function can be used to deactivate this.
You can also delete a cookie by updating its expiry time to a past date. Here’s an example of deleting a cookie immediately:
setcookie("my_first_cookie","", time() - 3600);
Does your browser allows cookies?
Here’s a simple way to check if your browser has enabled cookies:
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
Understanding PHP Sessions
The HTTP protocol does not keep a user’s status on a webpage. Sessions are used to solve the challenge of persisting and accessing a variable across several web pages. In this part, we’ll look at how to use PHP sessions to store and access values.
Starting a Session
In PHP, use the session start() method to initiate a session. This method starts a new session or returns to an existing one. It is critical to notice that this function must be called before any output is transmitted to the browser; otherwise, an error will be generated. Here’s an example of how to begin a session:
<?php
session_start();
Storing Data
After starting a session, you may utilize the $_SESSION global variable to save data in the session. The data is saved as key-value pairs, where the key is the variable name and the value is the data to be recorded. Here’s an example of data storage in a session:
<?php
session_start();
$_SESSION['username'] = "JohnDoe";
Retrieving Data
To retrieve data from a session, you can use the $_SESSION
global variable and access the key of the data that you want to retrieve. Here’s an example of retrieving data from a session:
<?php
session_start();
echo $_SESSION['username']; // will output "JohnDoe"
Deleting Data
To delete data from a session, you can unset the key of the data that you want to remove. Here’s an example of deleting data from a session:
<?php
session_start();
unset($_SESSION['username']);
Destroying a session
To destroy a session, you can use the session_destroy()
function. This function will remove all data stored in the session and end the session. Here’s an example of destroying a session:
<?php
session_start();
session_destroy();
Q&A
What is the purpose of cookies in PHP?
Cookies are small files stored on the client’s computer that can contain information related to the user, request, response, and server. They are sent along with requests to the server, allowing the server to identify the user.
How can we create a cookie in PHP?
PHP’s setcookie()
method is used to create a new cookie. It’s important to note that the first parameter, name
, is the only required one, while the rest of the parameters are optional.
How can we get the value of a cookie in PHP?
Cookies are stored in the $_COOKIE global variable in PHP. To get a cookie and its value, you can simply pass the name of the cookie to the global variable.
How can we delete a cookie in PHP?
You can set an expiry time for a cookie, after which it will be automatically deleted. You can also update the expiry time of a cookie to a past date in order to delete it immediately.
What is the purpose of sessions in PHP?
Sessions are used to persist and access a value across multiple web pages.
Exercises:
- What is the difference between a session and a cookie?
- How do you start a session?
- How do you set a session variable?
- How do you destroy a session?
- How do you set a cookie?
- How do you retrieve the value of a cookie?
- How do you unset a cookie?
Answers:
- A session is a way to store data on the server, while a cookie is a way to store data on the client’s computer. Sessions are typically used for authentication and authorization, while cookies are used for user preferences and tracking.
- To start a session in PHP, use the session_start() function.
- To set a session variable in PHP, use the $_SESSION superglobal array, like so: $_SESSION[‘variable_name’] = ‘value’;
- To destroy a session in PHP, use the session_destroy() function.
- To set a cookie in PHP, use the setcookie() function, like so: setcookie(‘cookie_name’, ‘value’, time() + (86400 * 30), ‘/’);
- To retrieve the value of a cookie in PHP, use the $_COOKIE superglobal array, like so: echo $_COOKIE[‘cookie_name’];
- To unset a cookie in PHP, use the setcookie() function with an expiration date in the past, like so: setcookie(‘cookie_name’, ”, time() – 3600);