PHP Cookies
What is a Cookie?
Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. A cookie is often used to identify a user. It is a small file that the server create on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain); setcookie() defines a cookie to be sent along with the rest of the HTTP headers.
<?php
setcookie("user", "Ashok Yadav", time()+3600);
?>
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
?>
Example2
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Ashok Yadav", $expire);
?>
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
setrawcookie()
setrawcookie - Send a cookie without urlencoding the cookie value
<?php setrawcookie('cookie_name', rawurlencode($value), time()+60*60*24*365); ?>