[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
PHPCookies
Cookies are a very useful mechanism to remember information. HTTP protocol is stateless protocol that is, once a page is requested by the client and served by the server, no information is kept. That is where cookies come into the scene. Cookies allow you to store information on the user’s hard disk.

If you need more information about cookies in general visit http://www.cookiecentral.com/faq/

When dealing with cookies in PHP you have to remember three things:

1. Setting and deleting a cookie before any output to the web browser is sent. 2. In order to access a cookie information you must refresh the page 3. A cookie can only be access either from the page it has set it or from all the pages in the sub folder from where the cookie has been set. More on this later.



Setting a cookie in PHP

Setting a cookie in PHP is very simple. Just use the setcookie command before any output to the web browser is sent.

<?php 
setcookie("uname", "Gaetano", time()+36000); 
?>


In this example three a cookie called uname is being set up. The value of uname will be “Gaetano”. The other parameter sets the value of the expiration date. Using the function time(), you get the current UNIX time stamp. I have added 36000 seconds to the UNIX time stamp so that the expiration time of the uname cookie will be of 10 hours.

Accessing a cookie

Accessing a cookie in PHP is very simple. You can get the cookie value using the $_COOKIE[] associative array. The key to use is the cookie name. The example below illustrates how to do this.

<?php
echo $_COOKIE[‘uname’]; //this will print Gaetano
?>


Deleting a cookie

In order to delete a cookie, use the setcookie function to set the expiry date to an hour ago. The cookie will be automatically deleted from the user’s hard disk.

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


This tutorial has ben produced by http://www.snippetcollection.com

last edited (September 24, 2005) by gaetanoc, Number of views: 2207, Current Rev: 2 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.