iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (34)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

May 16, 2008
Who Are Your Top Friends on Facebook?
About
 
May 15, 2008
Reader Question - Would you host your client's work on your website?
About
 
May 15, 2008
How to Create an Ajax Autocomplete Text Field: Part 6
WebReference.com
 
May 14, 2008
Poll: Are the browser safe colors still needed?
About
 
May 14, 2008
Google Doctype launched
About
 
May 14, 2008
Web Editor Reviews - 6 New Reviews
About
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /PHP /Cookies and Sessions

Basics of Setting Cookies with PHP 

  Views:    9144
  Votes:    3
by Kirill Talanov 11/21/03 Rating: 

Synopsis:

Cookies are useful for many things: they can keep track of where you've been, what forms you have filled in and they can even keep you logged in into a website! With this 'yummy' tutorial you will learn how to create, read and delete cookies from a user's hard drive.
Pages: firstback2 forwardlast
The Article

Setting Cookies

A cookie is basically a text file located on the visitor's computer used for various purposes by the website.

For instance, a cookie can hold your username for that website, and this is the example that this tutorial will be building on.

A cookie can be easily set using PHP's setcookie() function:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

The above shows how setcookie() should be used. First, you start the function by typing setcookie( , then you state the name of the cookie, the cookie's value and expiration date.
Keep in mind that anything in the [] square brackets is optional, but it is always a good practice to include the expiration date, and you will obviously want a cookie value (unless the cookie is being deleted).

Ready to set a cookie?

 <?php$name = "Mike"; setcookie("username",$name,time()+3600);?>

The code above sets a cookie called "username" with a value "Mike", which will expire in 3600 seconds (or 1 hour).

Now that we have a cookie set, the logical thing to do would be to "read" it.

Since the cookie is named "username", all we have to do to print out the value of the cookie is:

 <?phpecho $_COOKIE["username"];?>

Alternatively, you can use $name = $_COOKIE["username"];, this way you can do anything you wish with $name.

As you can see, reading cookies is extremely easy.

The next page will tell you how to delete cookies and how to avoid common mistakes.

Pages: firstback2 forwardlast

Similar/related articles:


 
  Sponsors