How to create a cookie in PHP

In this lesson we look at how to create a cookie in PHP.

We will start off with a very simple cookie called 'colour' which stores a value of 'orange'.

So, in this example, this could represent the favourite colour of the visitor to your website.

<?php
	setcookie('colour', 'orange');

Line 1: this is our opening PHP code block declaration.
Line 2: we set the cookie and pass in 2 arguments. The first is the name of the cookie and the second is the value.

In this example, the cookie will never expire. It will remain on the user's computer until such time as they delete it themselves.

 

Setting a Cookie Expiry Time

We can pass a third argument into the cookie, which is the expiry time of the cookie.

To do this we can get the current time using the time() function and then add a number of seconds.

In this example, I have added 600 seconds (10 minutes) to the current time.

So, the cookie will expire 600 seconds after it has been set.

<?php
	setcookie('colour', 'orange', time()+600);

 

Watch the Video Tutorials

Want to Learn More?

Become a member and get access to the member only area of this site here.

Comments

Your email address will not be published.

User Avatar

The video was extremely useful. Do you have any more?

by Lemon T, 18-Dec-2015

User Avatar

@Lemon T

Yes, there are a few on YouTube.

However, there is a full PHP for Beginners course you may wish to take a look at which contains over 130 lectures.

You will find details here: http://coding.academy/tutorials

by Patrick Morrow, 22-Dec-2015

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.