Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Create PHP Cookies I
- Syntax:
- setcookie($name, $value, $expire, $path);
- 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.
- Example:
- <!DOCTYPE html>
- <?php
- // Creating cookie
- setcookie("TempCookie", "PHPCookie", time()+1*24*60*60,'/') ;
- ?>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
- <title></title>
- </head>
- <body>
- <p>Testing of Cookie Creating </p>
- </br>
- <h3><p>Now retrieve the cookie value </p></h3>
- </br>
- <?php
- // Retrieve the cookie value with $_COOKIE[] function
- echo 'Cookie value is : '.$_COOKIE["TempCookie"];
- ?>
- </body>
- </html>
- In the example above the expiration time is set to a day (60 sec * 60 min * 24 hours * 1 day).
- Create PHP Cookies II (with Isset)
- <!DOCTYPE html>
- <?php
- // Creating cookie
- setcookie("UserTempCookie", "UserCookie", time()+1*24*60*60) ;
- ?>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
- <title>Cookie Test</title>
- </head>
- <body>
- <p>Testing of Cookie Creating </p>
- </br>
- <h3><p>Is Cookie value set? </p></h3>
- </br>
- <?php
- // check, is cookie set or not
- if(isset ($_COOKIE["UserTempCookie"]))
- echo 'Answer is : yes'.' '.'and cookie value is :'.$_COOKIE["UserTempCookie"];
- else
- echo 'Answer : No';
- ?>
- </body>
- </html>
- Deleting Cookie:
- When deleting a cookie you should assure that the expiration date is in the past.
- Let’s we have an example, how to delete cookie in PHP.
- Example:
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
- <title>Cookie Test</title>
- </head>
- <body>
- <?php
- setcookie("UserTempCookie","",time()-3600);
- echo 'Cookie deleted successfully';
- ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment