An Introduction to PHP

Cookies in PHP

Setting Cookies

The world wide web is stateless, which means it remembers nothing about you. The usual way of keeping track of user preferences is to use cookies. If you are setting a cookie, you must do it before the headers are written, so must be set at the very start of the document. Cookies are set in PHP using the setcookie function.

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

The cookies are not actually set in the page where they are written, but will be set in any subsequent pages. The following example sets a userName cookie, that expires after one hour.

<?php
    // Set a cookie that expires in one hour
    setcookie("userName", $name, time()+3600);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>PHP Cookies</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
A cookie was set on this page, and will be active when
the client has sent the cookie back to the server.
</p>
</body>
</html>

Reading Cookies

When a cookie is set, PHP uses the cookie name as a variable with the appropriate value. Accessing a cookie is just a simple case of referring to the cookie name as a variable. You can use the isset function to determine if a cookie has been set. The following example tests if the userName cookie has been set, and prints an appropriate message.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Accessing a Cookie</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    if (isset($userName))
        print "Welcome " . $userName . "<br>";
    else
        print "You are not logged in <br>";
?>
</p>
</body>
</html>

You might also like...

Comments

About the author

Gez Lemon United Kingdom

I'm available for contract work. Please visit Juicify for details.

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In theory, theory and practice are the same. In practice, they're not.”