HTTP
cookies. setcookie()
or setrawcookie()
function. Cookies are part of the HTTP
header, so setcookie()
must be called before any output is sent to the browser. PHP provided setcookie()
function to set a cookie. This function requires upto six arguments and should be called before <html> tag.
setcookie
(name, value, expire, path, domain, security);
The parameters of the setcookie()
function have the following :
Parameter | Description |
---|---|
name | The name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. |
value | The value of the cookie. Do not store sensitive information since this value is stored on the user's computer. |
expires | The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0. |
path | Specify the path on the server for which the cookie will be available. If set to / , the cookie will be available within the entire domain. |
domain | Specify the domain for which the cookie is available to e.g www.example.com. |
secure | This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP. |
<?php
setcookie("name", "V V Ramana Reddy", time()+3600, "/","", 0);
setcookie("age", "27", time()+3600, "/", "", 0);
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Cookies</title>
</head>
<body>
<?php
echo "Set Cookie"
?>
</body>
</html>
PHP provides many ways to access cookies. The PHP $_COOKIE
or $HTTP_COOKIE_VARS
superglobal variable is used to retrieve a cookie value. Following example will access all the cookies set in above example.
<!DOCTYPE html>
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
echo $_COOKIE["age"];
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome To : " . $_COOKIE["name"] . "<br />";
else
echo "Cookies Not recognized" . "<br />";
?>
</body>
</html>
To delete a cookie, use the setcookie()
function with an expiration date in the past:
<?php
setcookie( "name", "", time()- 250, "/","", 0);
setcookie( "age", "", time()- 250, "/","", 0);
?>
<!DOCTYPE html>
<html>
<head>
<title>Deleting Cookie with PHP</title>
</head>
<body>
<?php
echo "Cookie 'name' is deleted.";
?>
</body>
</html>
Our website is made possible by displaying ads to our visitors.
Please help us continue to provide you with free. So please disabling your ad blocker.