PHP’s Cookie handeling functions


Welcome to my first article for DevPapers. This tutorial will show you the basics of PHP’s cookie functions. I will cover main points such as setting cookies, printing cookie values and removing a cookie.

Let’s Get Eating!

As you know PHP uses functions to perform tasks. For cookie setting PHP uses the setcookie() function. Below is the syntax for setting a cookie in PHP.

setcookie ( name [, value [, expire [, path [, domain [, secure]]]]])

If this is your first time with PHP then the syntax may be confusing. Let me explain what we have up there. The name attribute of the function allows you to set the name of the cookie, this will make it possible to print out a cookie value later in this tutorial. The value attribute is the information which will be stored on the clients computer. The expire attribute is the time at which the cookie will expire and information held in the cookie will no longer be used. If this is not set then the cookie will expire when the browser closes. The path attribute is the path on the server which the cookie will be available on. Domain refers to the domain name on which the cookie is available, and finally the secure attribute (either 0 or 1) shows if the cookie should only be used over a secure (https) connection.

Setting Cookies

As explained on the previous page, the setcookie() function has many attributes. However only one is required, this is the name attribute.

<?php setcookie("CookieName"); ?>

The code above will set a cookie with the name CookieName, all cookies in PHP can be accessed using the $_COOKIE array. The syntax for this is as follows…


You would replace name with the name of the cookie, so for our first example this would be CookieName, then you would use the echo function to print out the value…

<?php echo "{$_COOKIE['CookieName']}"; ?>

Remember: If you are using double quotes to echo things out, remember to place {} around anything which contains single quotes or PHP will generate an error.

This concludes our very basic introduction to PHP’s cookie function setcookie(). You can find more information and examples on the PHP Manual.

About the Author: Martyn Coupland
A 17 year old web designer who has been making web sites for several years for his own use and for others. After he built a base on HTML he learned PHP and MySQL, two years later he now makes custom scripts for his PHP site.