- PHP Basics
- Learn PHP
- PHP Comments
- PHP Data Types
- PHP Variables
- PHP Operators
- PHP echo
- PHP print
- PHP echo vs. print
- PHP if else
- PHP switch
- PHP for Loop
- PHP while Loop
- PHP do...while Loop
- PHP foreach Loop
- PHP break and continue
- PHP Arrays
- PHP print_r()
- PHP unset()
- PHP Strings
- PHP Functions
- PHP File Handling
- PHP File Handling
- PHP Open File
- PHP Create a File
- PHP Write to File
- PHP Read File
- PHP feof()
- PHP fgetc()
- PHP fgets()
- PHP Close File
- PHP Delete File
- PHP Append to File
- PHP Copy File
- PHP file_get_contents()
- PHP file_put_contents()
- PHP file_exists()
- PHP filesize()
- PHP Rename File
- PHP fseek()
- PHP ftell()
- PHP rewind()
- PHP disk_free_space()
- PHP disk_total_space()
- PHP Create Directory
- PHP Remove Directory
- PHP Get Files/Directories
- PHP Get filename
- PHP Get Path
- PHP filemtime()
- PHP file()
- PHP include()
- PHP require()
- PHP include() vs. require()
- PHP and MySQLi
- PHP and MySQLi
- PHP MySQLi Setup
- PHP MySQLi Create DB
- PHP MySQLi Create Table
- PHP MySQLi Connect to DB
- PHP MySQLi Insert Record
- PHP MySQLi Update Record
- PHP MySQLi Fetch Record
- PHP MySQLi Delete Record
- PHP MySQLi SignUp Page
- PHP MySQLi LogIn Page
- PHP MySQLi Store User Data
- PHP MySQLi Close Connection
- PHP Misc Topics
- PHP Object Oriented
- PHP new Keyword
- PHP Cookies
- PHP Sessions
- PHP Date and Time
- PHP GET vs. POST
- PHP File Upload
- PHP Image Processing
Cookie in PHP with Examples
A cookie is a small piece of data that the server-side application stores on the client-side (i.e., on the user's web browser). Cookies are commonly used in web applications to store user-specific information such as login credentials, user preferences, or the contents of a shopping cart. On subsequent requests from the same client, the server can retrieve this information from the cookie.
How to set a cookie in PHP
The setcookie() function in PHP is used to set a cookie. The setcookie() function has the following basic syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
In the above general form of the "setCookie()" function, there are seven arguments, and following is a list and brief description of all seven arguments.
- name is the name of the cookie (string)
- value is the value of the cookie (string)
- expire is the expiration time of the cookie (integer timestamp)
- path is the path on the server where the cookie will be available (string, default is '/')
- domain is the domain where the cookie will be available (string, default is the current domain)
- secure is a flag indicating whether the cookie should only be transmitted over a secure HTTPS connection (boolean, default is false)
- httponly is a flag indicating whether the cookie should be inaccessible to client-side scripts (boolean, default is false)
Consider the following PHP code that demonstrates how to set a cookie in PHP:
setcookie("username", "william", time()+3600, "/");
The above PHP code creates a cookie called "username" with the value "william" on the server's root path. The above "setcookie()" function takes four arguments, which are briefly described below:
- "username" is the name of the cookie. In this case, it's "username".
- "william" is the value of the cookie. In this case, it's "william".
- time()+3600 is the expiration time of the cookie. This sets the cookie to expire in one hour (3600 seconds) from the current time. time() returns the current time as a Unix timestamp (i.e., the number of seconds since January 1, 1970). Adding 3600 to the current time gives us the timestamp for one hour from now.
- "/" is the path on the server where the cookie will be available. In this case, it's the root path of the server, which means the cookie will be available on all pages of the website.
How to retrieve a cookie in PHP
Use the PHP $_COOKIE superglobal array to retrieve the cookie. As an example:
$username = $_COOKIE["username"];
PHP Cookie Example
Here is an example illustrating how to create cookies in PHP.
<?php // Set the cookie name and value $cookieName = "fresherearth"; $cookieValue = "Computer Programmer"; // Set the expiration time for the cookie (30 days from now) $expirationTime = time() + (86400 * 30); // 86400 seconds = 1 day // Set the cookie with the above name, value, and expiration time setcookie($cookieName, $cookieValue, $expirationTime); // Check if the cookie exists and print a message accordingly if (!isset($_COOKIE[$cookieName])) { echo "Cookie not found. A new cookie has been created."; } else { echo "Cookie exists with the name: " . $cookieName . " and value: " . $_COOKIE[$cookieName]; } ?>
Here is the sample output of the above creating cookies example code in PHP. This is the screenshot of the sample output at the first run of the above PHP program in the web browser:
Now, if you run the above creating cookie program in PHP for the first time, a cookie with the name "fresherearth" and value "Computer Programmer" is created for 30 days. Therefore, if you re-run the same program or refresh your browser for the same program, you will see the following output this time:
If you create the above cookie for only 2 seconds, then you will see that your cookie will be created and expire in only 2 seconds. After creating your cookie for 2 seconds, if you refresh your browser after 2 seconds, you will see the message "Creating cookie.." after 2 seconds of creating your cookie using the above program in PHP.
Here is an example showing how to retrieve cookies in PHP.
<?php $cookieName = "fresherearth"; // Check if the cookie exists or not if (!isset($_COOKIE[$cookieName])) { // If the cookie doesn't exist, set it with a value and expiration time $cookieValue = "Computer Programmer"; $expirationTime = time() + (86400 * 30); // 86400 seconds = 1 day setcookie($cookieName, $cookieValue, $expirationTime); } // Retrieve the cookie value and print it along with the cookie name if (isset($_COOKIE[$cookieName])) { echo "Cookie is retrieving...<br>"; echo "Cookie is retrieved successfully...<br><br>"; echo "Name of the cookie = " . $cookieName . "<br>"; echo "Value of the cookie = " . $_COOKIE[$cookieName] . "<br>"; } else { echo "Error occurred...<br>"; echo "Exiting...<br>"; } ?>
Here is the sample output produced by the above retrieving cookie example code in PHP.
In PHP, use the isset() function on the superglobal variable $_COOKIE to determine whether or not a cookie has been set. Let's take an example of checking whether a cookie is already set or not.
<html> <head> <title>Checking cookie is set or not in PHP</title> </head> <body> <?php if (isset($_COOKIE['cookieName'])) { echo "Cookie is set<br>"; echo "You are ".$_COOKIE['cookieName']; } else { echo "Cookie is not set<br>"; echo "You can't proceed!"; } ?> </body> </html>
As the cookie is not set, here is the sample output produced by the above cookie example code in PHP.
Now try another example to check for cookies, whether they are set or not, on the user's computer in PHP.
<html> <head> <title>Checking cookie is set or not in PHP</title> </head> <body> <?php $cookieName = "fresherearth"; if (isset($_COOKIE[$cookieName])) { echo "Cookie is set<br>"; echo "You are ".$_COOKIE[$cookieName]; } else { echo "Cookie is not set<br>"; echo "You can't proceed!"; } ?> </body> </html>
As a result of the cookie named "fresherearth" being set by the example program for creating cookies, the output of the checking whether the cookie is set or not example code in PHP will be "true" this time.
To delete any cookie in PHP, just create the cookie again with the same name but set the expiration time to 1 hour ago or earlier, that is, set time as time()-3600.
Here is an example showing how to delete cookies in PHP from the user's computer.
<html> <head> <title>Delete Cookie Example in PHP</title> </head> <body> <?php $cookieName = "fresherearth"; setcookie($cookieName, "", time()-3600); echo "The cookie <b>$cookieName</b> is deleted successfully."; ?> </body> </html>
Here is an example of what the above PHP code for deleting a cookie produces.
Here is an example showing how to check whether the cookie is deleted or not in PHP.
<html> <head> <title>Check Cookie is deleted or not Example in PHP</title> </head> <body> <?php $cookieName = "fresherearth"; if(isset($_COOKIE[$cookieName])) { echo "The cookie <b>$cookieName</b> is not deleted."; } else { echo "The cookie <b>$cookieName</b> is deleted."; } ?> </body> </html>
Here is an example of what the above PHP example program does when it checks to see if the cookie has been deleted.
« Previous Tutorial Next Tutorial »