PHP Learn It! PHP Cookies
"Best Deal"

"Bored - Do You Agree?"

Bored - Studied Hard - Enjoy Yourself "TAKE A BREAK"

"Decide Now-So Many Choices"
"Amazing Deals"
Once You Know, You Newegg

Cooking Cookies with PHP

What is a cookie?

Learn PHP and MySQL fast!

Learn how you can start building rich interactive database driven sites like a professional developer easily and quickly...

>> Order your copy now for just $39.95 <<

A cookie is often used to store data which can be used to identify a user, for example, person's username.

Cookie is a small flat file which sits on user’s computer. Each time that user requests a page or goes to a webpage, all cookie information is sent too. This is used to identify who you are.

Example of cookie usage:

When you log into a website and check “remember me”, it will store your username (and other information about you) in a cookie. Next time when you come back to the same website, it knows who you are and will log you in automatically.

In this tutorial, we will learn how to write, read and delete cookies in PHP.

Creating a cookie

A cookie can be created using the setcookie function in PHP. Let’s explore this function.

setcookie($name, $value, $expire, $path, $domain, $secure) 

Creating a cookie with setcookie

setcookie("username", "john", time()+3600);


Cookie username is set with value john which is set to expire after one hour on users computer.

The function time() retrieves the current timestamp. Appending 3600 seconds (one hour) to the current time to make the cookie to expire after one hour.

Note: A cookie must be set before any HTML code as shown above.

Creating a permanent cookie

Lets create a cookie which is set to last for 1 year.

setcookie("username", "john", time()+(60*60*24*365));

Retrieving a cookie

Cookie information can retrieved using the predefined $_COOKIE array.

The following will retrieve our username cookie value

echo $_COOKIE["username"];



To print the entire $_COOKIE array, you can do the following

echo "<pre>";
echo "</pre>";


	[username] => john

Deleting a Cookie:

In order to delete cookies, you just set the cookie to expire in the past date.

Following will delete our username cookie.

setcookie("username", "john", time()-(60*60*24*365));

From HTML to PHP programming...
Learn how to build websites in PHP

<< PHP Date Top PHP Sessions >>