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 (35)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

September 7, 2008
Web Design Clinic - Art meets Webdesign
About
 
September 6, 2008
Browser safe colors - do we care?
About
 
September 6, 2008
Get a Daily CSS Tip
About
 
September 5, 2008
It's safe to use Google Chrome now
About
 
September 5, 2008
Add a comment
.net
 
September 5, 2008
The Partial Function Application in JavaScript
WebReference.com
 
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:    10051
  Votes:    4
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