What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds 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.
Facts
- You have to put the cookie code as the first line of your file, it has to be before the head, before any other code, HTML or PHP.
- The cookie will not work on the page until its refreshed, or the user visits the page again.
- The cookie only works on the directory you're in and down. Its best to place the cookie in a file which is located in the root directory, so you can use the cookie anywhere around the site.
setcookie(name, value, expire, path, domain);
Exmaples
setcookie ("cookie", "spoono rocks");
//makes a variable $cookie with a value of "spoono rocks"
setcookie ("cookie", "spoono rocks", time()+3600);
//same thing as above, but will last for 3600 seconds, or one hour from the current time.
Retrieve a cookie value.The PHP $_COOKIE variable is used to retrieve a cookie value.
setcookie ("cookie1", "spoono rocks once", time()+3600);
setcookie ("cookie2", "spoono rocks 2 times", time()+3600);
setcookie ("cookie3", "spoono rocks 3 times", time()+3600);
//Then in the main body, you can place:
echo $_COOKIE["cookie1"]; //will display "spoono rocks once"
echo $_COOKIE["cookie2"]; // "spoono rocks 2 times"
echo $_COOKIE["cookie3"]; // "spoono rocks 3 times"
//if you want to display all cookies for debugging
//you can use:
print_r($_COOKIE);Another Exampleif (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!
";
else
{
echo "Welcome guest!
";
setcookie("user", "Blogger", time()+3600);
}
///On first visit it will display guest and there after blogger.
Delete cookies
Just place a new setcookie() statement with the variable you want to deconstruct
setcookie ("cookie");
//deletes the spoono cookie
Copyright Ayon Baidya
No comments:
Post a Comment