Cookies in php application example

While developing php web application, cookie is one of the efficient ways of storing client information, so as developer we must know how cookie works in php code. here we learn about cookie in php, how to write cookies in php application, add and access cookie in php website.

setcookie($cookie_name, $cookie_value, time() + (86400 * 15), "/");
$_COOKIE[$cookie_name]
What is Cookie in php?

A cookie is a small file that store information in plain text format on the user's computer. a cookie is often used to identify a user in website when they revisit. When visitors start browsing your php application in browser, a small text file will be produced and stored in their computer.

How to create cookie in php website

Here you learn how to use cookies in php application, Create cookie, then write and read from cookie in php web application.

<?php            
$cookie_name = "username";
$cookie_value = "WebTrainingRoom";
setcookie($cookie_name, $cookie_value, time() + (86400 * 15), "/"); // 86400 = 1 day
?>
Modify a Cookie Value in Php

You just need to set (again) the cookie using the set cookie setcookie() function

<?php             
$cookie_name = "username";
$cookie_value = "WebTrainingRoom";
setcookie($cookie_name, $cookie_value, time() + (86400 * 15), "/"); // 86400 = 1 day
?>

So basically if you see the difference between create cookie and modify cookie, there is no difference, if the cookie does not exist with that particular key, it creates or else it overwrite

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set! <br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
Delete a Cookie in Php code

To delete a cookie, you just need to set null value for that particular key

<?php
// set the expiration date to one hour ago
setcookie("username", "", time() - 3600);
?>

Simple way to test php cookies in local environment is to write and read cookie on your webpage, check if values are written and retrieved properly

You may be interested in following php tutorials:

 
Php Cookies Examples
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course