If you are Learning PHP to make a web based application or making a website you need to know how to pass user information between different parts of the script. You can do this by using sessions an by using cookies.
Cookies are Small files left by the server on the client’s computer that can be use for different reasons like remembering the user information, what they have put in their basket,etc.
you can create a cookie by using setcookie() function:
setcookie ( $cookie_name , $value_stored_in_cookie , $expire_in_seconds = 0 , $path_available_to , $domain_available_to );
The function will return false if it fails to make the cookie or true id it succeed.
$cookie_name; as it suggests it is the name of the cookie and is the only part of the setcookie() function that has to be there the rest are optional.
$value_stored_in_cookie; It is the value stored in the cookie that can be accessed using $_COOKIE[‘cookie_name’] variable in PHP.
$expire_in_seconds; is an integer allowing you to define for how long is the cookie valid for example for for how long is the user logged in and after that it’s not. it uses timestamps so you can use time() function to get the current timestamp then add seconds that you want the cookie to be valid added to it like time()+7200 will make it available for 2 hours.
$path_available_to; this part will define what part of your site can access the cookie like /blog/ will only make the cookie available to the /blog/ part of the domain but script at /forum/ can not access it.
$domain_available_to; will define what domain can access this information, this way no other website can access the information set for your site alone.
OK now examples:
<?php
setcookie(“user”, “Harry Potter”, time()+3600);// will set the cookie for harry potter for one hoursetcookie(“book”,”some book”,time()+(3600*24));// this will make the cookie book with value of some book availible for 24 hours.
?>
You set the cookie now how to access it’s content? here is how:
<?php
echo $_COOKIE[‘user’];// will display Harry Potter
echo “<br />”;
echo $_COOKIE[‘book’];// will display some book
?>
Like other variables you can use isset() function to find out if the cookie has been set or not like:
<?php
setcookie(‘user’,”Sam”,time()+3600);// setting the cookie
if(isset($_COOKIE[‘user’])){
echo “You are Loged in “.$_COOKIE[‘user’];
}else{
echo “Loged out”;
}
?>
To delete the cookie you can change the expiration time to the passed to make sure that the cookie is expired:
<?php
setcookie(‘user’,””,time()-3600);// this will expires the cookie
?>