Cookies and Session in PHP are used to store the data and that are available throughout the site. Cookies and Session in PHP are stored on the client’s browser and web server respectively.
In this article, we learn the following topic:
- Purpose of Cookies
- Setting Cookies
- Retrieving Cookies
- Deleting Cookies
- Storing Arrays in Cookies
- Retrieving Arrays in Cookies
- Session in PHP
- Starting a Session in PHP
- Storing and Retrieving Session Data
- Destroying Certain and Complete Session data
- Difference between Session and Cookie in PHP
Purpose of Cookies
A cookie is a small file that is stored by the webserver on the client’s browser. You can get the name and value of the cookie on all pages if you set a cookie. You can generate and retrieve cookie values using PHP.
Tracking: You can track OS, Browser, location, IP, also can track pages which the user visits.
Analytics: Based on the tracked data you can analyze to serve various kinds of data for greater value.
Setting Cookies in PHP
We use
setcookie()
function to set a cookie in PHP.
Syntax:
setcookie(Name, Value, Expire, Path, Domain, Secure, httponly);
Here are all the arguments in detail:
Name: Required. This is the name of the cookie.
Value: Required. It is the value of a cookie that stores on the client’s computer. It retrieves by cookie name.
Expire: We use this to set the cookie expiry time. It is optional.
Path: We use this to set the path. The forward slash “/” indicates that the cookie is made available on the entire domain. It is optional.
Domain: We use this to specify the domain, the cookie is for. It is optional
Security: Used to indicate the cookie should only be sent if there is a secure HTTPS connection. It is optional.
Let’s take an example:
1 2 3 4 | <?php setcookie("userName", "Troposal", time()+ 120,'/'); //It will be expire after 120 seconds echo "The cookie has been set."; ?> |
In the above example, the cookie has been set for 120 seconds.
Retrieving Cookies in PHP
We can retrieve cookie value by
$_COOKIE
superglobal variable.
1 2 3 | <?php echo $_COOKIE["userName"]; ?> |
Deleting Cookie in PHP
To deleting the cookie, you can add a past date in expiration time.
1 2 3 4 | <?php setcookie("userName", "", time() - 120);//Set expiration time echo "The cookie has been deleted."; ?> |
Storing Arrays in Cookies
We need to encode the array data using
json_encode
function to store the data in cookies.
Example:
1 2 3 4 5 6 7 8 9 | <?php $arrData = array( 'userName' => 'Troposal', 'visitedPages' => 'Home,ContactUs' ); $value = json_encode($arrData); setcookie("userName", json_encode($arrData)); echo "The cookie has been set."; ?> |
Retrieving Arrays in Cookies
We will retrieve cookie value and decode it using
json_decode
function before use.
Example:
1 2 3 4 | <?php $value = json_decode($_COOKIE['userDetail']); print_r($value); ?> |
Session in PHP
The session is a global variable that stores on the server. Session variables last by default until the user closes the browser. The session is generally used for logging in the user and show the data based on that user. It is also used on the shopping website to store the cart value of the user in the session.
Starting a Session in PHP
We use
start_session()
function to start a session in PHP. It creates a new session id for the user.
1 2 3 | <?php start_session(); ?> |
Storing and Retrieving Session Data
The session is stored in a key-value pair by using
$_SESSION
superglobal variable.
Example of storing data:
1 2 3 4 5 | <?php session_start(); $_SESSION["userName"] = "Troposal"; $_SESSION["userId"] = 12345; ?> |
Example of retrieving data:
1 2 3 4 5 6 | <?php session_start(); echo 'User Name:' . $_SESSION["userName"]; echo '<br>'; echo 'User ID:' . $_SESSION["userId"]; ?> |
Destroying Certain and Complete Session data
The unset is an in-built function for deleting variable in PHP. For example, you want to destroy UserId from session then use unset($_SESSION[“userId”]).
Example:
1 2 3 4 5 6 | <?php session_start(); if(isset($_SESSION["userId"])){ unset($_SESSION["userId"]); } ?> |
For destroying the complete session, we use the
session_destroy()
function.
1 2 3 4 | <?php session_start(); session_destroy(); ?> |
Difference between Cookies and Session in PHP
Cookies | Sessions |
---|---|
Cookies are stored in the client’s browser. | Sessions are stored on the webserver. |
The Limit amount of data is stored. The maximum official cookie size is 4 KB | More amount of data is stored. In sessions, it holds multiple variables. |
We can access the values of the cookie easily. So it is less secure. | We can not access the session values easily. So it is more secure. |
We set past time to expire the cookie. | We use
session_destory()
function to destroy the sessions. |