PHP Cookies Tutorial

Reply

Join Date: Nov 2008
Posts: 1
Reputation: devon.philip is an unknown quantity at this point 
Solved Threads: 0
devon.philip devon.philip is offline Offline
Newbie Poster

PHP Cookies Tutorial

 
0
  #1
Nov 25th, 2008
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.
Reply With Quote Quick reply to this message  
Join Date: Sep 2007
Posts: 1,538
Reputation: cwarn23 has a spectacular aura about cwarn23 has a spectacular aura about cwarn23 has a spectacular aura about 
Solved Threads: 137
cwarn23's Avatar
cwarn23 cwarn23 is offline Offline
Posting Virtuoso

Re: PHP Cookies Tutorial

 
0
  #2
Nov 25th, 2008
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.
  1. <?
  2. $dbhost='localhost'; //database host (usually localhost)
  3. $accountname='root'; //database username.
  4. $password=''; //database password
  5. $database='my_database'; //database name - not table
  6.  
  7. //configure the above variables.
  8.  
  9.  
  10. $linkID = @mysql_connect($dbhost,$accountname,$password)
  11. or die("Could not connect to MySQL server");
  12. @mysql_select_db($database) or die("Could not select database");
  13.  
  14. mysql_query('CREATE TABLE `'.$database.'`.`cookies` (`name` TEXT NOT NULL, `value` TEXT NOT NULL,
  15. `ip` TEXT NOT NULL, `expires` TEXT NOT NULL) ENGINE = MyISAM') or die(mysql_error());
  16. echo "Table named 'cookies' has been created successfully."
  17. ?>

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.
  1. $dbhost='localhost';
  2. $accountname='root';
  3. $password='';
  4. $database='my_database';
  5.  
  6. $linkID = @mysql_connect($dbhost,$accountname,$password)
  7. or die("Could not connect to MySQL server");
  8. @mysql_select_db($database) or die("Could not select database");
  9.  
  10. function ssl_cookie_make($cookies_minutes_till_expire,$cookies_houres_till_expire,$cookies_days_till_expire,$cookiename,$cookievalue)
  11. {
  12. $cookiename=str_replace("'",'"',$cookiename);
  13. $cookies_months_till_expire=0;
  14. $cookieexpiresy=date(Y);
  15. $cookieexpiresm=date(m)+$cookies_months_till_expire;
  16. $cookieexpiresj=date(j)+$cookies_days_till_expire;
  17. $cookieexpiresg=date(G)+$cookies_houres_till_expire;
  18. $cookieexpiresi=date(i)+$cookies_minutes_till_expire;
  19. if ($cookieexpiresi>59)
  20. {
  21. while ($cookieexpiresi>59)
  22. {
  23. $cookieexpiresg+=1;
  24. $cookieexpiresi-=60;
  25. }
  26. }
  27. if ($cookieexpiresg>24)
  28. {
  29. while ($cookieexpiresg>24)
  30. {
  31. $cookieexpiresj+=1;
  32. $cookieexpiresg-=24;
  33. }
  34. }
  35. if ($cookieexpiresj>30)
  36. {
  37. while ($cookieexpiresj>30)
  38. {
  39. $cookieexpiresm+=1;
  40. $cookieexpiresj-=31;
  41. }
  42. }
  43. if ($conkieexpiresm>12)
  44. {
  45. while ($cookieexpiresm>12)
  46. {
  47. $cookieexpiresy+=1;
  48. $cookieexpiresm-=12;
  49. }
  50. }
  51. mysql_query("INSERT INTO `cookies` SET `name`='".$cookiename."', `value`='".$cookievalue."', `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."',
  52. `expires`='".$cookieexpiresy.",".$cookieexpiresm.",".$cookieexpiresj.",".$cookieexpiresg.",".$cookieexpiresi."'");
  53. }
  54.  
  55. function ssl_cookie_value($cookiename)
  56. {
  57. $cookiename=str_replace("'",'"',$cookiename);
  58. $cookiesql=mysql_query("SELECT * FROM `cookies`");
  59. $cookiedateexplode=explode(',',date(Y.','.m.','.j.','.G.','.i));
  60. while ($cookierow=mysql_fetch_array($cookiesql))
  61. {
  62. $cookiesqlexplode=explode(',',$cookierow['expires']);
  63. if ($cookiesqlexplode[0]<=$cookiedateexplode[0] && $cookiesqlexplode[1]<=$cookiedateexplode[1] && $cookiesqlexplode[2]<=$cookiedateexplode[2]
  64. && $cookiesqlexplode[3]<=$cookiedateexplode[3] && $cookiesqlexplode[4]<=$cookiedateexplode[4])
  65. {
  66. mysql_query("DELETE FROM `cookies` WHERE `expires`='".$cookierow['expires']."'");
  67. // AND `ip`='".$cookierow['ip']."' AND `name`='".$cookierow['name']."' AND `value`='".$cookierow['value']."'
  68. }
  69. unset($cookiesqlexplode);
  70. }
  71. unset($cookiedateexplode);
  72.  
  73. $cookieresult=mysql_query("SELECT `value` FROM `cookies` WHERE `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."' AND `name`='".$cookiename."'");
  74. $cookierow=mysql_fetch_array($cookieresult);
  75. return $cookierow['value'];
  76. }
  77.  
  78. function ssl_cookie_changevalue($cookiename,$cookienewvalue)
  79. {
  80. $cookiename=str_replace("'",'"',$cookiename);
  81. mysql_query("UPDATE `cookies` SET `value`='".$cookienewvalue."' WHERE `name`='".$cookiename."' AND `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."'");
  82. }
  83.  
  84. function ssl_cookie_changeexpire($cookiename,$cookies_minutes_till_expire,$cookies_houres_till_expire,$cookies_days_till_expire)
  85. {
  86. $cookiename=str_replace("'",'"',$cookiename);
  87. $cookies_months_till_expire=0;
  88. $cookieexpiresy=date(Y);
  89. $cookieexpiresm=date(m)+$cookies_months_till_expire;
  90. $cookieexpiresj=date(j)+$cookies_days_till_expire;
  91. $cookieexpiresg=date(G)+$cookies_houres_till_expire;
  92. $cookieexpiresi=date(i)+$cookies_minutes_till_expire;
  93. if ($cookieexpiresi>59)
  94. {
  95. while ($cookieexpiresi>59)
  96. {
  97. $cookieexpiresg+=1;
  98. $cookieexpiresi-=60;
  99. }
  100. }
  101. if ($cookieexpiresg>24)
  102. {
  103. while ($cookieexpiresg>24)
  104. {
  105. $cookieexpiresj+=1;
  106. $cookieexpiresg-=24;
  107. }
  108. }
  109. if ($cookieexpiresj>30)
  110. {
  111. while ($cookieexpiresj>30)
  112. {
  113. $cookieexpiresm+=1;
  114. $cookieexpiresj-=31;
  115. }
  116. }
  117. if ($conkieexpiresm>12)
  118. {
  119. while ($cookieexpiresm>12)
  120. {
  121. $cookieexpiresy+=1;
  122. $cookieexpiresm-=12;
  123. }
  124. }
  125. mysql_query("UPDATE `cookies` SET `expires`='".$cookieexpiresy.",".$cookieexpiresm.",".$cookieexpiresj.",".$cookieexpiresg.",".$cookieexpiresi."'
  126. WHERE `name`='".$cookiename."' AND `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."'");
  127.  
  128.  
  129. $cookiesql=mysql_query("SELECT * FROM `cookies`");
  130. $cookiedateexplode=explode(',',date(Y.','.m.','.j.','.G.','.i));
  131. while ($cookierow=mysql_fetch_array($cookiesql))
  132. {
  133. $cookiesqlexplode=explode(',',$cookierow['expires']);
  134. if ($cookiesqlexplode[0]<=$cookiedateexplode[0] && $cookiesqlexplode[1]<=$cookiedateexplode[1] && $cookiesqlexplode[2]<=$cookiedateexplode[2]
  135. && $cookiesqlexplode[3]<=$cookiedateexplode[3] && $cookiesqlexplode[4]<=$cookiedateexplode[4])
  136. {
  137. mysql_query("DELETE FROM `cookies` WHERE `expires`='".$cookierow['expires']."'");
  138. // AND `ip`='".$cookierow['ip']."' AND `name`='".$cookierow['name']."' AND `value`='".$cookierow['value']."'
  139. }
  140. unset($cookiesqlexplode);
  141. }
  142. unset($cookiedateexplode);
  143. }

Then of course there is using these functions. Below is the code showing the use of each function.
  1. //This function creates a server-side cookie.
  2. //ssl_cookie_make(mins_expire, houres_expire, days_expire, cookie_name, cookie_value);
  3. ssl_cookie_make(6,0,0,'cookie name','value');
  4.  
  5. //This function returns the value of a cookie for this particular user.
  6. ssl_cookie_value('cookie name');
  7.  
  8. //This function changes the cookie value for this particular user.
  9. ssl_cookie_changevalue('cookie name','new value');
  10.  
  11. //This function changes when the cookie expires for this particular user.
  12. //ssl_cookie_changeexpire(cookie_name,mins_expire, houres_expire, days_expire);
  13. ssl_cookie_changeexpire('cookie name',0,-9,0);
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.
Try not to bump 10 year old threads as it can be really annoying.
http://syntax.cwarn23.net/
Smilies: ^_* +_+ v_v -_- *~*`
My favourite PC. - Oopy Doopy Do 2U2!
Reply With Quote Quick reply to this message  
Join Date: Sep 2005
Posts: 1,083
Reputation: digital-ether is just really nice digital-ether is just really nice digital-ether is just really nice digital-ether is just really nice 
Solved Threads: 66
Moderator
digital-ether's Avatar
digital-ether digital-ether is offline Offline
Veteran Poster

Re: PHP Cookies Tutorial

 
0
  #3
Nov 30th, 2008
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
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!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the PHP Forum


Views: 1063 | Replies: 2
Thread Tools Search this Thread



Tag cloud for PHP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC