Using Cookies in PHP

Page content

Cookies in PHP

Cookies are commonly used by websites to store and remember information about the users that visit their website. Using session variables and cookies allow you to remember settings about the user like their preferences, their customization options, their login information, etc. You can also store other data like browser type, IP address, and the type of operating system being used with JavaScript. Cookies are mostly handled using Javascript and PHP or ASP.

To create a cookie using PHP, you have to use the setcookie() function.

The setcookie() function is used to set a cookie using certain parameters like the name, the value and the expiration time.

The exact syntax of the setcookie() function is

setcookie(cookie_name, cookie_value, expiration_time);

The following is an explanation of the variables used in this function.

  • cookie_name: The name of your cookie
  • cookie_value: The value stored in your cookie
  • expiration_time: The time in which your cookie will expire

For example, to create a cookie which stores the name of the visitor, you can use this code

<?php// getting the name from the form variable

$username = $_POST[‘username’];

// creating the expiration time for the cookie to 10 days from now

$exptime = 60 * 60 * 24 * 10 + time();

//creating a cookie with the name ‘username’

setcookie(‘username’,$username,$exptime);

?>

This creates a cookie username which stores the user’s name from the form and sets the expiration date to 10 days from now. The time() function is used to return the current time.

To retrieve the value of a cookie which has already been created, you can use the PHP $_COOKIE variable.

The $_COOKIE variable stores the names and values of all existing cookies in an associative array.

The value of a cookie with the name cookie_name is stored in $_COOKIE[“cookie_name”].

To print the value of the username cookie, just use the echo function:

<?php

echo $_COOKIE[“username”];

?>

To check if a particular cookie exists, use the isset() function. It returns TRUE if the cookie value has been set.

Thus, you can use this code to welcome a returning user using his name and to greet new users differently.

<?php

if (isset($_COOKIE[“username”]))

echo “Hi " . $_COOKIE[“username”] . “, Welcome to Bright Hub again.”;

else

echo “Hi, welcome to Bright Hub.”;

?>

This will display different messages depending on whether the user is old or new.

To delete a cookie, you can use the setcookie() function but set the expiration time to some past value.

You could set the expiration time to time()-60, which is one minute in the past.

For example,

<?php

$exptime = time()-60;

//creating a cookie with the name ‘username’

setcookie(‘username’,“dummyvalue”,$exptime);

?>

This will delete the username cookie.