Create a website RSS feed

PHP Cookies

PHP Cookies

Last update on: 09-25-2008
A cookie is often used to identify a user. Cookies must be sent before any calls or other html output. They are stored on the computer of your visitor, and can insert a small amount of information.

The cookies retain the pattern of variables, as explained in a previous course, variable_name = variable_value, but other parameters are also defined in a cookie:

to send a cookie, we use the PHP function named setcookie ()

Example:

We will send a cookie with the variable $visitor whose value iTeachWeb.
<?php
setcookie("visitor","iTeachWeb","/");
?> 

In this example, the cookie can be displayed on every page of the site, by using the "/"

Now! we will send a cookie, keeping the same variable, but with an expiration of 1 year

Example:

 <?php
setcookie("visitor","iTeachWeb",time()+365 * 24 * 3600 , "/");
?>

How it works?

First, you have visitor, it's the name of your variable for this cookie, iTeachWeb is its value, next you have time() this is the locally time (see the dates lesson), So in this example, time()+ is the time and date + 365 days x 24 hours x 3600 seconds (60 seconds times 60 minutes to get 1 hour), So the cookie expires in 1 year.

How to get the cookie?

Very simple, You get the cookie by calling its name.

Example of how to get a cookie:

We use the same cookie (visitor), with its value (iTeachWeb).
<?php
print $_COOKIE['visitor'].' is my cookie';
?> 

will display on the screen

iTeachWeb is my cookie.

Very easy ah! :-)

How to delete a cookie?

So easy too, you send a cookie with a variable without value and with an exceeded expiration date.

Example:

<?php
setcookie("visitor","",time()-3600,"/");
?> 

Now the cookie is no more in your visitor's computer.

To your keyboards and start typing and coding.

PHP and MySQL's lessons:

Introduction To PHP
Get Started With PHP
PHP Variables
PHP Variables Of Environment
PHP Conditions
PHP Looping
PHP Cookies
PHP Working With Dates
PHP Working With Arrays
PHP Working With Files
PHP Play With Strings
PHP And Forms
Send Emails With PHP
The Include Statement
Get Started With MySQL
MySQL Update And Delete
The WHERE Clause
MySQL Functions
Guestbook Script
Websites Directory Script
Multiple Pages With PHP
Create Your Forum With Php

Banner HomeServices Contact |  ©2009 http://www.iteachweb.net/