Php Cookie Tutorial

A COOKIE is a piece of data that the browser saves on the user's machine, usually in a temporary folder. Cookies can be useful as they store persistent data you can access from different pages of your Website, but at the same data they are not as secure as data saved in a server (like SESSION does).

You can create a cookie using setcookie() with this syntax:

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

For setcookie() only name and value are mandatory. Expire, path, domain, secure, httponly are optional.

You can use the $_COOKIE superglobal to access your cookies.


Setting a cookie:

//setting a cookie called username, with value of johnDoe that will last for 2 weeks
setcookie('username', 'johnDoe', time() +(60*60*24*14) );

Accessing a cookie:

//storing the value of the username cookie into a variable
if( isset($_COOKIE['username']) )
$username = $_COOKIE['username'];

Deleting a cookie:

To delete a cookie, you must set it again with same exact parameters, but with
EXPIRE set to a date in the past (e.g. previous month)

setcookie('username', 'johnDoe', time() - (60*60*24*30) ); //notice the minus here

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

Copyright © 2015 by Cramerz.com.