PHP COTW: cookies

In this weeks PHP code of the week we cover the use of cookies; how to create, add, extract and delete them.

Cookies are one of the ways that you can store information about a user and use that information on another page. They work by creating a text file on a user’s computer and retrieving that information when been called by in other pages. Cookies have the ability to expire at a certain time which can be set by the code creating them.

Below is an example of how we set a cookie and in this example the cookie contains a username and password.

$username = “Alex”;
$password = “mypass”;
$cookie_data = $username . '-' . $password;

if(setcookie("cookie_info", $cookie_data, time()+3600) == FALSE) {

echo "You computer does not support cookies.";

}

We have $username and $password set and we are combining the username and password values with a hyphen in between them.

We use the setcookie() function to set the cookie and specify the cookie name (cookie_info), the value that it will be assigned ($cookie_data) and the time it will expire (the current time + 3600 seconds which is 1 hour).  Other paramarters you can specify are the domain and path the cookie is only allowed to be accessed from, if the cookie can only be sent over HTTPs or only by a HTTP connection.

The setcookie function is wrapped in an if statement which allows us to perform an action if setting the cookie was unsuccessful, in this case it would print out “You computer does not support cookies”.

You can check if there is a cookie present by using the isset command we covered in our earlier PHP code of week. We can the cookie by using $_COOKIE[‘name’].

if (isset($_COOKIE['cookie_info'])) {

$cookie_info = explode("-", $_COOKIE['cookie_info']);
$username = $cookie_info[0];
$password = $cookie_info[1];

}

If the cookie is present we can extract the cookies information. We have both the username and password in a string, so we use the explode function to break the string into username and password.

Say once a user logs out and we want to delete the cookie we can use the set cookie function and we just can just set the expiration time to be 1 hour ago so that it will remove the cookie straight away. We don’t need to specify a value as we want the cookie to contain no information.

if (isset($_COOKIE['cookie_info'])) {

setcookie ("cookie_info", "", time() - 3600);

}

There you have an overview on how to use cookies. In the next PHP code of the week we’ll talk about using sessions, another way to store and retrieve user information.

Leave a Reply