Cookies in PHP
What is a cookie
Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.
Uses of cookie
Cookies are often used to perform following tasks:
- Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
- User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is 'Retargetting'. A concept used in online marketing, where depending upon the user's choice of content, advertisements of the relevant product, which the user may buy, are served.
- Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.
How to create a cookie in PHP
PHP has a
setcookie() function to send a cookie. We will discuss this function in detail now.
setcookie(name, value, expire, path, domain, secure, httponly)
setcookie() has several parameters. Following table discusses those.
|Parameter||Description||Which type of data|
|name||Name of the cookie.||String|
|value||Value of the cookie, stored in clients computer.||String|
|expire||Unix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch).||Integer|
|path||Server path in which the cookie will be available.||String|
|domain||To which domain the cookie is available.||String|
|secure||If set true, the cookie is available over a secure connection only.||Boolean|
setcookie() returns boolean.
Following example shows how to create a cookie in PHP. Code first and then some explanation.
<?php $cookie_value = "w3resource tutorials"; setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1); if (isset($_COOKIE['cookie'])) echo $_COOKIE["w3resource"]; ?>
So, what does the code above does? The first parameter sets the name of the cookie as 'w3resource', the second parameter sets the value as 'w3resource tutorials', the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server '/home/your_name' where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.
echo $_COOKIE["w3resource"]; simply prints the cookie value. This way you can retrieve a cookie value.
How to create a cookie without urlencoding the cookie value
setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use
This function has all the parameters which setcookie() has, and the return value is also boolean.
PHP $_COOKIE autoglobal
If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.
The following code shows how to use $_COOKIE.
<?php $cookie_value = "w3resource tutorials"; setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1); echo 'Hi ' . htmlspecialchars($_COOKIE["w3resource"]); ?>
If you wish to retreive all the cookies, you may use the following command
<?php print_r($_COOKIE); ?>
PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like "...headers already sent....".
To get rid of the problem, you may use "Output buffering functions". Following code shows how to add an output buffering function.
<?php ob_start(); //at the begining of the php script //your code goes here //add these two lines at the end of the script $stuff = ob_get_clean(); echo $stuff; ?>
How to delete a cookie
To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.
<?php $cookie_value = "w3resource tutorials"; setcookie("w3resource", $cookie_value, time()-3600, "/home/your_usename/", "example.com", 1, 1); ?>
Cookies vs Sessions
Both cookies and sessions are used for storing persistent data. But there are differences for sure.
Sessions are stored on server side. Cookies are on the client side.
Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.
Sessions are safe that cookies. Because, since stored on client's computer, there are ways to modify or manipulate cookies.
Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.
PHP: Tips of the Day
PHP: Saving image from PHP URL
If you have allow_url_fopen set to true:
$url = 'http://example.com/image.php'; $img = '/my/folder/flower.gif'; file_put_contents($img, file_get_contents($url));
Else use cURL:
$ch = curl_init('http://example.com/image.php'); $fp = fopen('/my/folder/flower.gif', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp);
Ref : https://bit.ly/2Q93gK6
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook