| | |
PHP Cookies Tutorial
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
•
•
Join Date: Nov 2008
Posts: 1
Reputation:
Solved Threads: 0
A cookie is a flat file that stores tiny bits of information. It is stored on the client’s machine and is passed to the client when they visit your site. Each cookie can store anything from usernames to number of visits to a site. This tutorial will teach you how to create, retrieve, display, and delete cookies using php
1. Create a Cookie using PHP
Cookies are created using the setcookie() function. Below is an example of the setcookie() function
setcookie($name, $value, $expired, $path, $domain, $secure)
There are values that you can pass into the setcookie() function. The values are: name of the cookie, value of the cookie, the date the cookie expires, path where the cookie is available on the server, domain where the cookie is available, and where it is coming from a secure page.
The three values that we are worried about are $name, $value, and $expired.
Below is the php code to create a php cookie named "username". We set the value of the cookie to "Tom", and set the expiration date at one hour from now.
<?php
setcookie("username", "Tom", time()+3600);
?>
The cookie is set through the browser once a client visits your site or page that you set the cookie on.
2. Retrieve & Display a Cookie using PHP
Now let’s retrieve & display the cookie we just set. We retrieve the cookie using the predefined $_COOKIE array. Then we display the cookie using the echo function. Here is the code that will get you the cookie.
<?php
echo $_COOKIE["username"];
//http://www.infysolutions.com
?>
3. Delete a cookie using PHP
We can delete the cookie when we are finished with it. Cookies are deleted by simply setting the expiration date to a past date. The example below will delete the cookie named username.
<?php
setcookie("username", "Tom", time()-(60*60*24*365));
?>
That’s it! You have just created a cookie on the client’s machine, retrieved & displayed the cookie and deleted the cookie once you were done with it.
1. Create a Cookie using PHP
Cookies are created using the setcookie() function. Below is an example of the setcookie() function
setcookie($name, $value, $expired, $path, $domain, $secure)
There are values that you can pass into the setcookie() function. The values are: name of the cookie, value of the cookie, the date the cookie expires, path where the cookie is available on the server, domain where the cookie is available, and where it is coming from a secure page.
The three values that we are worried about are $name, $value, and $expired.
Below is the php code to create a php cookie named "username". We set the value of the cookie to "Tom", and set the expiration date at one hour from now.
<?php
setcookie("username", "Tom", time()+3600);
?>
The cookie is set through the browser once a client visits your site or page that you set the cookie on.
2. Retrieve & Display a Cookie using PHP
Now let’s retrieve & display the cookie we just set. We retrieve the cookie using the predefined $_COOKIE array. Then we display the cookie using the echo function. Here is the code that will get you the cookie.
<?php
echo $_COOKIE["username"];
//http://www.infysolutions.com
?>
3. Delete a cookie using PHP
We can delete the cookie when we are finished with it. Cookies are deleted by simply setting the expiration date to a past date. The example below will delete the cookie named username.
<?php
setcookie("username", "Tom", time()-(60*60*24*365));
?>
That’s it! You have just created a cookie on the client’s machine, retrieved & displayed the cookie and deleted the cookie once you were done with it.
Although cookies are useful for long-term storage, I find that people can so easily disable them making your site not work. That is why I have invented what I call server-side cookies. These are cookies all stored within a mysql database and a retrieved by the users ip address. To help extend this topic I shall post the code for server-side cookies and explain how to use them. First you will need to create the mysql database which can be done just by configuring and running/executing the following code.
So after configuring the mysql variables at the top of that code and running/executing that code, you then may delete the file containing the above code. Then next is to add the functions to be able to use server-side cookies. So place the following code near the top of the page.
Then of course there is using these functions. Below is the code showing the use of each function.
As you can see, the above code box explains itself and these cookies can only last for untill the person logs off the internet which is about 1-2 days.
I thought I would share this with everybody and since this topic is about a cookies tutorial this place would suite best.
php Syntax (Toggle Plain Text)
<? $dbhost='localhost'; //database host (usually localhost) $accountname='root'; //database username. $password=''; //database password $database='my_database'; //database name - not table //configure the above variables. $linkID = @mysql_connect($dbhost,$accountname,$password) or die("Could not connect to MySQL server"); @mysql_select_db($database) or die("Could not select database"); mysql_query('CREATE TABLE `'.$database.'`.`cookies` (`name` TEXT NOT NULL, `value` TEXT NOT NULL, `ip` TEXT NOT NULL, `expires` TEXT NOT NULL) ENGINE = MyISAM') or die(mysql_error()); echo "Table named 'cookies' has been created successfully." ?>
So after configuring the mysql variables at the top of that code and running/executing that code, you then may delete the file containing the above code. Then next is to add the functions to be able to use server-side cookies. So place the following code near the top of the page.
php Syntax (Toggle Plain Text)
$dbhost='localhost'; $accountname='root'; $password=''; $database='my_database'; $linkID = @mysql_connect($dbhost,$accountname,$password) or die("Could not connect to MySQL server"); @mysql_select_db($database) or die("Could not select database"); function ssl_cookie_make($cookies_minutes_till_expire,$cookies_houres_till_expire,$cookies_days_till_expire,$cookiename,$cookievalue) { $cookiename=str_replace("'",'"',$cookiename); $cookies_months_till_expire=0; $cookieexpiresy=date(Y); $cookieexpiresm=date(m)+$cookies_months_till_expire; $cookieexpiresj=date(j)+$cookies_days_till_expire; $cookieexpiresg=date(G)+$cookies_houres_till_expire; $cookieexpiresi=date(i)+$cookies_minutes_till_expire; if ($cookieexpiresi>59) { while ($cookieexpiresi>59) { $cookieexpiresg+=1; $cookieexpiresi-=60; } } if ($cookieexpiresg>24) { while ($cookieexpiresg>24) { $cookieexpiresj+=1; $cookieexpiresg-=24; } } if ($cookieexpiresj>30) { while ($cookieexpiresj>30) { $cookieexpiresm+=1; $cookieexpiresj-=31; } } if ($conkieexpiresm>12) { while ($cookieexpiresm>12) { $cookieexpiresy+=1; $cookieexpiresm-=12; } } mysql_query("INSERT INTO `cookies` SET `name`='".$cookiename."', `value`='".$cookievalue."', `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."', `expires`='".$cookieexpiresy.",".$cookieexpiresm.",".$cookieexpiresj.",".$cookieexpiresg.",".$cookieexpiresi."'"); } function ssl_cookie_value($cookiename) { $cookiename=str_replace("'",'"',$cookiename); $cookiesql=mysql_query("SELECT * FROM `cookies`"); $cookiedateexplode=explode(',',date(Y.','.m.','.j.','.G.','.i)); while ($cookierow=mysql_fetch_array($cookiesql)) { $cookiesqlexplode=explode(',',$cookierow['expires']); if ($cookiesqlexplode[0]<=$cookiedateexplode[0] && $cookiesqlexplode[1]<=$cookiedateexplode[1] && $cookiesqlexplode[2]<=$cookiedateexplode[2] && $cookiesqlexplode[3]<=$cookiedateexplode[3] && $cookiesqlexplode[4]<=$cookiedateexplode[4]) { mysql_query("DELETE FROM `cookies` WHERE `expires`='".$cookierow['expires']."'"); // AND `ip`='".$cookierow['ip']."' AND `name`='".$cookierow['name']."' AND `value`='".$cookierow['value']."' } unset($cookiesqlexplode); } unset($cookiedateexplode); $cookieresult=mysql_query("SELECT `value` FROM `cookies` WHERE `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."' AND `name`='".$cookiename."'"); $cookierow=mysql_fetch_array($cookieresult); return $cookierow['value']; } function ssl_cookie_changevalue($cookiename,$cookienewvalue) { $cookiename=str_replace("'",'"',$cookiename); mysql_query("UPDATE `cookies` SET `value`='".$cookienewvalue."' WHERE `name`='".$cookiename."' AND `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."'"); } function ssl_cookie_changeexpire($cookiename,$cookies_minutes_till_expire,$cookies_houres_till_expire,$cookies_days_till_expire) { $cookiename=str_replace("'",'"',$cookiename); $cookies_months_till_expire=0; $cookieexpiresy=date(Y); $cookieexpiresm=date(m)+$cookies_months_till_expire; $cookieexpiresj=date(j)+$cookies_days_till_expire; $cookieexpiresg=date(G)+$cookies_houres_till_expire; $cookieexpiresi=date(i)+$cookies_minutes_till_expire; if ($cookieexpiresi>59) { while ($cookieexpiresi>59) { $cookieexpiresg+=1; $cookieexpiresi-=60; } } if ($cookieexpiresg>24) { while ($cookieexpiresg>24) { $cookieexpiresj+=1; $cookieexpiresg-=24; } } if ($cookieexpiresj>30) { while ($cookieexpiresj>30) { $cookieexpiresm+=1; $cookieexpiresj-=31; } } if ($conkieexpiresm>12) { while ($cookieexpiresm>12) { $cookieexpiresy+=1; $cookieexpiresm-=12; } } mysql_query("UPDATE `cookies` SET `expires`='".$cookieexpiresy.",".$cookieexpiresm.",".$cookieexpiresj.",".$cookieexpiresg.",".$cookieexpiresi."' WHERE `name`='".$cookiename."' AND `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."'"); $cookiesql=mysql_query("SELECT * FROM `cookies`"); $cookiedateexplode=explode(',',date(Y.','.m.','.j.','.G.','.i)); while ($cookierow=mysql_fetch_array($cookiesql)) { $cookiesqlexplode=explode(',',$cookierow['expires']); if ($cookiesqlexplode[0]<=$cookiedateexplode[0] && $cookiesqlexplode[1]<=$cookiedateexplode[1] && $cookiesqlexplode[2]<=$cookiedateexplode[2] && $cookiesqlexplode[3]<=$cookiedateexplode[3] && $cookiesqlexplode[4]<=$cookiedateexplode[4]) { mysql_query("DELETE FROM `cookies` WHERE `expires`='".$cookierow['expires']."'"); // AND `ip`='".$cookierow['ip']."' AND `name`='".$cookierow['name']."' AND `value`='".$cookierow['value']."' } unset($cookiesqlexplode); } unset($cookiedateexplode); }
Then of course there is using these functions. Below is the code showing the use of each function.
php Syntax (Toggle Plain Text)
//This function creates a server-side cookie. //ssl_cookie_make(mins_expire, houres_expire, days_expire, cookie_name, cookie_value); ssl_cookie_make(6,0,0,'cookie name','value'); //This function returns the value of a cookie for this particular user. ssl_cookie_value('cookie name'); //This function changes the cookie value for this particular user. ssl_cookie_changevalue('cookie name','new value'); //This function changes when the cookie expires for this particular user. //ssl_cookie_changeexpire(cookie_name,mins_expire, houres_expire, days_expire); ssl_cookie_changeexpire('cookie name',0,-9,0);
I thought I would share this with everybody and since this topic is about a cookies tutorial this place would suite best.
Try not to bump 10 year old threads as it can be really annoying.
http://syntax.cwarn23.net/
My favourite PC. - Oopy Doopy Do 2U2!
http://syntax.cwarn23.net/
Smilies: ^_* +_+ v_v -_- *~*` My favourite PC. - Oopy Doopy Do 2U2!
A lot of people get on the net with IPs that change very often, dial-up, mobile phones, wireless networks, different locations etc. There's are also single IPs that can be used for multiple clients when they are behind a NAT.
Also to consider:
There are client side storage facilities other then cookies that are being standardized and/or implemented.
Examples:
http://www.whatwg.org/specs/web-apps...t-side-storage
https://developer.mozilla.org/en/DOM/Storage
Implementation in JS:
http://dojotoolkit.org/node/115
Also to consider:
There are client side storage facilities other then cookies that are being standardized and/or implemented.
Examples:
http://www.whatwg.org/specs/web-apps...t-side-storage
https://developer.mozilla.org/en/DOM/Storage
Implementation in JS:
http://dojotoolkit.org/node/115
www.fijiwebdesign.com - web design and development and fun
Cpanel Email - Let users Register email accounts on your website upon registration
Ajax Chat - Fully browser based chat!
Cpanel Email - Let users Register email accounts on your website upon registration
Ajax Chat - Fully browser based chat!
![]() |
Similar Threads
- creating cookies using curl-php (PHP)
- Ton's of spywarea nd SLOW IE 6 (Viruses, Spyware and other Nasties)
- WIN98SE protection (Viruses, Spyware and other Nasties)
- explorer, iexplore don't start (Viruses, Spyware and other Nasties)
- Help! My Computer is Infested with Spyware/Viruses (Viruses, Spyware and other Nasties)
- login script using sessions (PHP)
- how to make member expire after so many days with php script (PHP)
- how can i used session and cookies ??? (PHP)
Other Threads in the PHP Forum
- Previous Thread: Encryption in PHP
- Next Thread: php: abstract classes (whats the point behind them)
Views: 1063 | Replies: 2
| Thread Tools | Search this Thread |
Tag cloud for PHP
.htaccess access ajax apache api array beginner binary broken cakephp checkbox chrelad class cms code cron curl database date directory display download dynamic echo email error file files folder form forms function functions google href htaccess html image include insert integration ip java javascript joomla jquery limit link list login loop mail menu methods mlm mod_rewrite multiple mysql oop parse paypal pdf php phpmyadmin problem query radio random recursion regex remote script search select seo server sessions sms soap source space speed sql structure syntax system table tutorial update updates upload url validation validator variable video web webdesign xml youtube






