irwan

Create and Delete Cookies with PHP

May 9th, 2012
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.20 KB | None | 0 0
  1. Create PHP Cookies I
  2.  
  3. Syntax:
  4.  
  5. setcookie($name, $value, $expire, $path);
  6.  
  7. Here, $name specifies the name of cookie, $value specifies the value of cookie, $expire specifies the cookie expiration time and $path specifies the creating path of cookie. The ‘/’ sign is used for creating cookie in current domain.
  8. Example:
  9.  
  10. <!DOCTYPE html>
  11.  
  12. <?php
  13. // Creating cookie
  14.    setcookie("TempCookie", "PHPCookie", time()+1*24*60*60,'/') ;
  15.  ?>
  16. <html>
  17.     <head>
  18.         <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  19.         <title></title>
  20.     </head>
  21.     <body>
  22.         <p>Testing of Cookie Creating </p>
  23.         </br>
  24.         <h3><p>Now retrieve the cookie value </p></h3>
  25.         </br>
  26.         <?php
  27.         // Retrieve the cookie value with $_COOKIE[] function
  28.             echo 'Cookie value is : '.$_COOKIE["TempCookie"];
  29.        ?>
  30.     </body>
  31. </html>
  32.  
  33. In the example above the expiration time is set to a day (60 sec * 60 min * 24 hours * 1 day).
  34.  
  35.  
  36.  
  37.  
  38.  
  39. Create PHP Cookies II (with Isset)
  40.  
  41. <!DOCTYPE html>
  42. <?php
  43. // Creating cookie
  44.    setcookie("UserTempCookie", "UserCookie", time()+1*24*60*60) ;
  45.  ?>
  46.  
  47. <html>
  48.     <head>
  49.         <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  50.         <title>Cookie Test</title>
  51.     </head>
  52.     <body>
  53.         <p>Testing of Cookie Creating </p>
  54.         </br>
  55.         <h3><p>Is Cookie value set?  </p></h3>
  56.         </br>
  57.         <?php
  58.             // check, is cookie set or not
  59.         if(isset ($_COOKIE["UserTempCookie"]))
  60.             echo 'Answer is : yes'.' '.'and cookie value is :'.$_COOKIE["UserTempCookie"];
  61.         else
  62.             echo 'Answer : No';
  63.         ?>
  64.     </body>
  65. </html>
  66.  
  67.  
  68.  
  69.  
  70.  
  71. Deleting Cookie:
  72. When deleting a cookie you should assure that the expiration date is in the past.
  73. Let’s we have an example, how to delete cookie in PHP.
  74. Example:
  75.  
  76. <!DOCTYPE html>
  77. <html>
  78.     <head>
  79.         <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  80.         <title>Cookie Test</title>
  81.     </head>
  82.     <body>
  83.         <?php
  84.              setcookie("UserTempCookie","",time()-3600);
  85.              echo 'Cookie deleted successfully';
  86.         ?>
  87.     </body>
  88. </html>
Advertisement
Add Comment
Please, Sign In to add comment