Botturn PHP Programing

All About PHP, Tutorials, Scripts, Video Lessons, Forum, Downloads


TUTORIAL - Using Cookies in PHP

Posted by admin On April - 6-2009

A cookie is a file that is created by the site user's computer containing data for later use by the site.

An example of use of sites that create cookies are cookies that you do not need to enter your password when you access it again. Usually cookies are also used to store user preferences on the site.

Let's see how usua them in PHP:

Creating a cookie

To create a cookie is used to setcookie ().

The basic syntax of it is:

? View Code PHP
  nome_do_cookie , valor , expiracao ) ; setcookie (nome_do_cookie, value, expiration); 

The "expiration" is optional and corresponds to a date / time in timestamp format.

Thus, we could create a single cookie as follows:

? View Code PHP
  "botturn" , "OK" ) ; setcookie ("botturn", "OK"); 

Warning: setcookie () must be called before any HTML output, otherwise you will result in the fatal error "Can not modify header information".

On page, the cookie recuperariamos as follows:

? View Code PHP
  $_COOKIE [ "botturn" ] ; Meu_cookie $ = $ _COOKIE ["botturn"];
 " ; echo "$ meu_cookie"; 

Creating a cookie with date / time to expiration

? View Code PHP
  "botturn" , "OK" , time ( ) + 3600 ) ; setcookie ("botturn", "OK," Time () + 3600); 

The cookies would expire over one hour (3600 seconds is equal to one hour).

Deleting a cookie

When you delete a cookie, you should make sure that the expiration date has already passed it.

So both could delete cookies previously created as follows:

? View Code PHP
  "botturn" , "OK" , time ( ) - 3600 ) ; setcookie ("botturn", "OK," Time () - 3600); 

Popularity: 4% [ ? ]

Related posts Brought to you by Yet Another Related Posts Plugin .

Leave a Reply