Pages

PHP Cookies

A cookie is used to identify a user.Some information about the website's user are stored at the user's computer so whenever the same user sends the request through a browser software, the stored cookie can be utilized to identify that user.
Like every good web programming language, PHP also provides a very useful and easy mechanism to accomplish the concept of cookies.The setcookie() function will create a cookie in client computer, it is must that the setcookie() function should be called before the HTML beginning code.

The PHP setcookie Function
Have a look at the syntax of PHP setcookie() function below:


setcookie($key,$value,$expire);

where $key is the name of the cookie, $value is it's value and $expire is the time the cookie should remain alive on the user's computer.

<?php
setcookie("name","zaibi",time()+3600);
?>
<html>
<body>
<?php
echo "Welcome ".$_COOKIE["name"];
?>
</body>
</html>
Shown above is the complete example of how to set and retrieve a cookie in PHP.The setcookie function creates the cookie after the creation of a cookie it can be retrieved in any of the page of the website with array variable $_COOKIE.Another optional parameter of the PHP setcookie() function is time()+3600 which is making the cookie to remain alive till the current time plus 3600 seconds.To kill a cookie the time of past can be used like time()-1 etc.

 

0 comments:

Post a Comment