PHP Tutorial: Cookies
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
Creating a Cookie
PHP provides full support for cookies. Creating a cookie is a simple matter, but there is an important timing consideration to remember. If you are going to send a cookie down to the user's system, you must send it down before you send anything else; before any part of the page itself is sent, even before a blank line! A cookie is sent by using the setcookie( ) function. Here's an example:
setcookie ("cookiename", "This text will be in the cookie");
<head> ....... etc.
Reading a cookie
When a user visits a PHP page that could read a cookie that is present in the user's computer at the time they call for the page, PHP automatically reads the cookie into a variable named the same as the cookie, but prefixed with a $ sign. (Note that for this reason you should follow PHP variable naming conventions when creating your cookies - no spaces, for example!) So, to read our cookie, we would simply reference it's variable name like this:
print "our cookie says $cookiename";
This would show up on the page as:
our cookie says This text will be in the cookie
Deleting a cookie
When cookies are created, they are set by default to be deleted when the user closes their browser. You can override that default by setting a time for the cookie's expiration like this:
setcookie ("cookiename", "This text will be in the cookie", time( ) + 3600);
<head> ....... etc
The addition of the time( ) parameter followed by a plus sign and a number of seconds sets the amount of time from now at which point the cookie is to expire. In our example, the cookie will expire one hour from now.
There may be occasions when you need to delete a cookie before the user closes their browser, and before its expiration time arrives. To do so, you would use the setcookie( ) function with the appropriate name for the cookie and with a time( ) parameter with a negative number, like this:
setcookie ("cookiename", "", time( ) - 1);
Notice that we have left the contents parameter in its proper place, but with nothing in it. Remember also that the setcookie( ) function call has to come before anything else on the web page.
Being able to manipulate cookies, we will now be able to manipulate information within a user's session, remembering it from page iteration to iteration, and from page to page.