saftutorials.com
PHP COOKIES Tutorial

The PHP Cookies are commonly used for identifying a user at the server. It is a small file which is embedded on a users computer by the server. When ever a machine requests a page through a browser from the server, it sends cookie also. By using PHP we can create, retrieve and delete cookies.

Syntax of Cookies
This PHP setcookie() function is used for set cookie and can have seven parameters.
setcookie(cookie_name, cookie_value, expire_time, path, domain, secure, httponly);


Example for set cookie

<?php
// Set Cookie
$cookie_key = "employee";
$cookie_val = "John Pitt";
setcookie($cookie_key, $cookie_val, time() + (86400 * 30), "/"); // This cookie will expire after 30 day
?>
<!DOCTYPE html>
<html>
<body>
<h1>Set Cookies example</h1>
<?php
echo "Cookie Key : ".$cookie_key."<br />";
echo "Cookie Value : ".$_COOKIE[$cookie_key]."<br />";
echo "Cookie Value : ".$_COOKIE['employee'];
?>
</body>
</html>

The above code produces the following results

Outputs: Cookie Key: employee

Cookie Value: John Pitt

Cookie Value: John Pitt


Example for update cookie value

<?php
// Set Cookie
$cookie_key = "employee";
$cookie_val = "John Smith";
setcookie($cookie_key, $cookie_val, time() + (86400 * 30), "/"); // This cookie will expire after 30 day
?>
<!DOCTYPE html>
<html>
<body>
<h1>Update Cookies value</h1>
<?php
echo "Cookie Key : ".$cookie_key."<br />";
echo "Cookie Value : ".$_COOKIE[$cookie_key]."<br />";
echo "Cookie Value : ".$_COOKIE['employee'];
?>
</body>
</html>

The above code produces the following results

Outputs: Cookie Key: employee

Cookie Value: John Smith

Cookie Value: John Smith


Example for delete cookie

<?php
// Delete Cookie
$cookie_key = 'employee'
// Set expiration time before half an hour
setcookie($cookie_key, time() - 1800);
?>
<!DOCTYPE html>
<html>
<body>
<h1>Delete Cookies value</h1>
<?php
if($_COOKIE[$cookie_key])
echo $cookie_key." Cookie has been deleted";
else
echo $cookie_key." Cookie is available";
?>
</body>
</html>

The above code produces the following results

Outputs: employee Cookie has been deleted


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic