PHP Cookies

Cookies are small files that are created by the browser and stored on the client's computer. Cookies are useful for tailoring a website to a particular user. It is a way for the web page to remember a user and some information about him or her.

For example, you could use cookies to remember a user's username for them, so they don't have to type it in everytime they visit the login page.

Have a look at the PHP cookies tutorial below to help get you started.

PHP Setting a Cookie - setcookie Syntax

You must call the setcookie function before your script starts to output any data. That is, before any print or echo statements.

setcookie(name, value, expire, path, domain);

For most of the time, you won't need to specify the last 2 parameters in the function.

PHP Setting a Cookie Example

Let us set a cookie and dive right into some serious PHP programming:

$expire = time()+ 60; // current time plus 60 seconds
setcookie("name", "John Doe", $expire);
if (isset($_COOKIE["name"]))
    echo "I remember you " . $_COOKIE["name"] . "!<br />";
    echo "You're new around here";

The first time you visit the page (or every minute after that when the cookie expires) you will see:

You're new around here

If you view the page again within a minute of seeing the first message you will see:

I remember you John Doe!

That's all there is to setting cookies in PHP.

Deleting a cookie in PHP

Suppose you set a cookie with a much longer life and you want to delete it. All you do is set the same cookie again, but this time with a expiry date that is in the past.

// set the expiration date to one minute ago
setcookie("name", "", time()- 60);

Run that code and the cookie is lost and forgotten.

Not all browsers support cookies or have them enabled

Be careful when coding websites that rely heavily on cookies. Not all browsers support cookies (although most modern ones do) and not all users have cookies turned on in their browsers. You don't want to have a situation where your site does not work at all for a user simply because they do not have cookies turned on.

Try to write your code so that cookies add extra functionality and that no cookies will give regular functionality.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...