Home >>Advance PHP Tutorial >PHP Set Cookie
A cookie is a text file saved to a user's system by a Web site. This file contains information that the site can retrieve on the user's next visit, thereby allowing the site to "recognize" the user and provide an enhanced set of features customized to that specific user.
The setcookie( ) function is used to set a cookie. Note : The setcookie( ) function must use BEFORE the <html> tag. Syntax
setcookie(cookiename, value, expire, path, domain);
In the given example, create a cookie named "cookie_user" and assign the value "abhi" to it. We also specify that the cookie should expire after one hour. Eg
<?php setcookie("cookie_name", "abhi", time()+60*60); //OR $expire=time()+60*60; etcookie("cookie_name", "abhi", $expire); ?>
Explain : In the example above cookie_name variale creates and assign value inside variable is "abhi" which work for 1 hour.
The $_COOKIE[ ] super global variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "cookie_name" and display it on a page:
<?php // Print a cookie echo "Welcome ".$_COOKIE["cookie_name"]; ?>
Note : It works for 1 hour after 1 hour cookie deleted automatically and if you try to access after destroyed cookie it gives an error message.
<?php //set cookie setcookie("user", $_POST['n'] , time()+60*60); setcookie("age", $_POST['a'], time()+60*60); setcookie("profile", $_POST['prof'], time()+60*60); ?> <html> <body> <form method="post"> Enter your name <input type="text" name="n"/><hr/> Enter your age <input type="text" name="a"/><hr/> Enter your profile <input type="text" name="prof"/><hr/> <input type="submit" value="SET COOKIE"/> </form> </body> </html>
<?php print_r($_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", "abhi", time()-60*60); ?>