PHP HOME
PHP Introduction
PHP SETUP
PHP Syntax
PHP Data Types
PHP Outputs
PHP Variable
PHP Constant
PHP Strings
PHP Operators
PHP if else if
PHP Switch
PHP while loop
PHP for loop
PHP Arrays
PHP Functions
PHP Sorting Array
PHP Form Handling
PHP Form Validation
PHP Form Required
PHP Form URL/EMAIL
PHP Form Submit
PHP Contact Form
PHP DATE & TIME
PHP INCLUDE
PHP FILE HANDLING
PHP FILE OPEN/READ
PHP FILE CREATE/WRITE
PHP FILE UPLOAD
PHP SESSION
PHP COOKIES
PHP FILTER
PHP ERROR HANDLING
PHP EXCEPTION
PHP Redirects
PHP with MySQL
PHP WITH MYSQL DB
MYSQL CONNECT
MYSQL CREATE DATABASE
SELECT DATABASE
MYSQL CREATE TABLE
MYSQL INSERT DATA
MYSQL SELECT DATA
MYSQL UPDATE DATA
MYSQL DELETE DATA
MYSQL ORDER
MYSQL LIMIT
MYSQL LAST ID
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);
<?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
<?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
<?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