i

PHP Tutorial

PHP Cookies Handling

PHP cookies are a mechanism to store the user data in a remote browser and then it helps to track or identify the users who return to the webpage. PHP supports HTTP cookies transparently and they are part of HTTP header. So, basically it helps to identify the user.

Cookies is a small file that will be embedded on the user system through server and whenever the same user returns to the webpage, it again sends a cookie. Using PHP, you can create and retrieve those cookies values.

1 Creating and Retrieving a Cookie

Creating a cookie or sending a cookie in PHP is accomplished through setCookie() function. You need to use this function before

tag.

Syntax: setCookie( name, value, expire, path, domain, secure, httponly);

In the above syntax:

  • Name specifies the name of the cookie.

  • Value sets the value of the cookie and is stored on client’s computer.

  • Expire describe the value when cookie will expire. If this parameter is not given, the cookie expires after web browser if closed.

For example: setCookie(“username”, “dazzle”, time() + 60*60*24*5); // 5 days expiry

Name is a required parameter in this function and all other parameters are optional and the browser fills the values with reasonable default values automatically.

You can retrieve the cookie “username” with the global variable $_COOKIE and you can also use isset() function to check if the cookie is set or not.

For example:

$cookie_name = “username”;

$cookie_value = “dazzle”;

setCookie($cookie_name, $cookie_value, time() + 60*60*24*10 , “/”);

?>

if(!isset($_COOKIE[$cookie_name]))

 {
    echo "Cookie named '" . $cookie_name . "' is not set!";

else

{
    echo "Cookie '" . $cookie_name . "' is set!
";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
 

2 Modify a Cookie Value

To modify the cookie value just set the cookie again using the same setCookie function. The name of the cookie will remain same and the value of the cookie will be updated to the new value. For example:

$cookie_name = "username";
$cookie_value = "Sebastian";
setCookie($cookie_name, $cookie_value, time() + 60*60*24*10);
?>

3 Deleting a Cookie

If you want to delete a cookie, you can set the cookie with an expiration date that has already gone such as a time in the past. You can also check if a cookie is enabled or disabled using count function with the $_COOKIE variable. If $_COOKIE count is greater than 0 then cookies are enabled else disabled.

For example:

setCookie(“username”, “dazzle” , time() – 1800); //expiration date half an hour ago

?>

echo “ Cookie ‘username’ is deleted.”;

?>