Copyright © 2005-2008 Andrea Tincani

AndreaPHP | Forum | News | Downloads | Register | Help | Member List | Statistics | Search | PM | Profile

Print This Topic
Previous Topic (regexp to filter IP)Next Topic (Regular Expression for validating email addresses) New Topic New Poll Post Reply
AndreaPHP Forum : PHP General : Cookie How to
Poster Message
bambolin
Level: Trainee

Registered: 29-09-2005
Posts: 3

icon Cookie How to

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);
?>


----
Tutorial by
www.snippetcollection.com TEAM :-)

____________________________
http://www.snippetcollection.com - Free snippets and examples. Learn a new language by example

29-09-2005 at 06:04 PM
View Profile Send Email to User Show All Posts Visit Homepage | Quote Reply
AndreaPHP Forum : PHP General : Cookie How to
Previous Topic (regexp to filter IP)Next Topic (Regular Expression for validating email addresses) New Topic New Poll Post Reply
Surf To:


Not Logged In? Username: Password: Lost your password?
Partners: AndreaVB

Copyright © 2005-2008 Andrea Tincani

Powered by: tForum tForum Edition b0.92p1
Originally created by Toan Huynh (Copyright © 2000)
Enhanced by the tForumHacks team.