PHP Cookies-1
PHP Cookies-1
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the client
computer. They are typically used to keep track of information such as a username that the site can
retrieve to personalize the page when the user visits the website next time. A cookie can only be
read from the domain that it has been issued from. Cookies are usually set in an HTTP header but
JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie()
function needs to be called prior to any output generated by the script otherwise the cookie will not
be set.
Parameters: The setcookie() function requires six arguments in general which are:
Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury Car to
it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
Other Example:
<?php
// Set a cookie with name "username" and value "John"
$expire = time() + (60 * 60 * 24 * 30); // 30 days from now
$path = '/';
$domain = $_SERVER['HTTP_HOST'];
$secure = true; // HTTPS only
$httponly = true; // HTTP only
setcookie('username', 'John', $expire, $path, $domain, $secure, $httponly);
// Display a message
echo 'Cookie created with name "username" and value "JohnDoe"';
?>
In this example, we use the setcookie() function to create a cookie with the name "username" and
the value "JohnDoe". We also set some additional parameters:
expire: The expiration time of the cookie is calculated as 30 days from now using time() + (60 * 60 *
24 * 30).
path: The path on the server where the cookie will be available is set to /, meaning it will be available
on the entire domain.
domain: The domain that the cookie is available to is set to $_SERVER['HTTP_HOST'], which
automatically sets the domain to the current domain.
secure: The secure parameter is set to true, meaning that the cookie will only be sent over a secure
HTTPS connection.
httponly: The httponly parameter is set to true, meaning that the cookie will only be accessible
through HTTP requests and not through client-side scripts like JavaScript.
Only the name argument in the setcookie() function is mandatory. To skip an argument, the
argument can be replaced by an empty string(“”).
Retrieve a Cookie
$_COOKIE array stores all the cookies with cookie name as the key. Below is the syntax to get the
cookie value.
Syntax: $_COOKIE["cookiename"];
➢ Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a cookie
is set or not before accessing its value. Therefore to check whether a cookie is set or not, the
PHP isset() function is used. To check whether a cookie “Auction_Item” is set or not, the
isset() function is executed as follows:
Example: This example describes checking whether the cookie is set or not.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE superglobal variable
is used. It is an associative array that contains a record of all the cookies values sent by the browser
in the current request. The records are stored as a list where the cookie name is used as the key. To
access a cookie named “Auction_Item”, the following code can be executed.
Example: This example describes accessing & modifying the cookie value.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Deleting Cookies:
The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie()
function is called by passing the cookie name and other arguments or empty strings but however
this time, the expiration date is required to be set in the past. To delete a co okie named
“Auction_Item”, the following code can be executed.
</body>
</html>
Other Example:
<?php
// Start a session
session_start();
// Delete the "username" cookie by setting the expiration time to a value in the past
$expire = time() - 3600; // 1 hour ago
$path = '/';
$domain = $_SERVER['HTTP_HOST'];
$secure = true; // HTTPS only
$httponly = true; // HTTP only
setcookie('username', '', $expire, $path, $domain, $secure, $httponly);
// Display a message
echo 'Session and cookie deleted';
?>
In this example, we first unset the $_SESSION['username'] variable and destroy the session using
session_destroy() to ensure that the session data is removed.
Next, we delete the "username" cookie by setting its expiration time to a value in the past using the
setcookie() function. We also set the same parameters that we did when creating the cookie: path,
domain, secure, and httponly. Setting the cookie's value to an empty string ('') effectively removes
the cookie.
Finally, we display a message to the user confirming that the session and cookie have been deleted.
➢ Note that it's important to set the path, domain, secure, and httponly parameters to the same
values that were used when the cookie was created in order to ensure that the correct cookie
is deleted.
➢ If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end of
the session i.e. when the browser closes.
The same path, domain, and other arguments should be passed that were used to create the cookie
in order to ensure that the correct cookie is deleted.
// Display a message
echo 'Session cookie created with session ID: ' . $session_id;
?>
expire: The expiration time of the cookie is calculated as one hour from now using time() + (60 * 60).
path: The path on the server where the cookie will be available is set to /, meaning it will be available
on the entire domain.
domain: The domain that the cookie is available to is set to $_SERVER['HTTP_HOST'], which
automatically sets the domain to the current domain.
secure: The secure parameter is set to true, meaning that the cookie will only be sent over a secure
HTTPS connection.
httponly: The httponly parameter is set to true, meaning that the cookie will only be accessible
through HTTP requests and not through client-side scripts like JavaScript.
By setting these parameters, we increase the security and reliability of the session cookie.
Note that it's important to set the secure and httponly parameters appropriately based on the
security requirements of your application. Additionally, you should set the path and domain
parameters to restrict the scope of the cookie as needed.
<?php
// Set a cookie with name "username" and value "John"
$expire = time() + (60 * 60 * 24 * 30); // 30 days from now
$path = '/';
$domain = $_SERVER['HTTP_HOST'];
$secure = true; // HTTPS only
$httponly = true; // HTTP only
setcookie('username', 'John', $expire, $path, $domain, $secure, $httponly);
When this script is executed, it first sets a cookie with the name "username" and the value "John"
using the setcookie() function. The cookie is set to expire in 30 days ($expire = time() + (60 * 60 * 24
* 30)), and is accessible from the root path ($path = '/'). The domain is set to the current domain of
the server using $_SERVER['HTTP_HOST'], and the cookie is set to be accessible only via HTTPS
($secure = true) and HTTP ($httponly = true) requests.
Next, the script checks if the "username" cookie is set using the isset() function. If the cookie is set,
it retrieves the value of the cookie using $_COOKIE['username'] and stores it in a variable called
$username. It then displays a message to the user welcoming them back with their username using
echo "Welcome back, $username!";. If the cookie is not set, the script displays a message indicating
that no username cookie was found using echo "No username cookie found.";.
In summary, this PHP script sets a cookie with a name and value, and retrieves the value of the
cookie if it is set. It also sets additional parameters to increase the security and reliability of the
cookie.
Check if a Cookie is Set
Setcookies first
<?php
// set cookie named "language" with value "english" and an expiration time of 24 hours
setcookie("language", "english", time() + 86400);
Create a PHP script that checks if the cookie named language is set or not. If the cookie is set, disp lay
its value on the screen. If the cookie is not set, display a message indicating that the cookie is not
set.
<?php
// check if the cookie named "language" is set
if (isset($_COOKIE['language'])) {
// if the cookie is set, display its value on the screen
$language = $_COOKIE['language'];
echo "The value of the 'language' cookie is: " . $language;
} else {
// if the cookie is not set, display a message indicating that the cookie is not set
echo "The 'language' cookie is not set.";
}
?>