cookie used to identify the user.
What Cookie that?
cookie used to identify the user. A cookie is a server on the user's computer to stay in a small file. Whenever the same computer via the browser requests a page, this computer will send a cookie. By PHP, you can create and retrieve cookie values.
How to Create a Cookie?
setcookie () function is used to set the cookie.
Note: setcookie () function must be in the <html> tag before.
setcookie(name, value, expire, path, domain);
In the following example, we will create a cookie named "user" and assign it "w3big". We also provides this cookie expire after one hour:
<?php setcookie("user", "w3big", time()+3600); ?> <html> .....
Note: When sending cookie, the value of the cookie will automatically be URL encoded, decoded when retrieved automatically.(To prevent the URL encoding, use setrawcookie () instead.)
You can also set the cookie expiration time in another way. This may be simpler than using seconds manner.
<?php $expire=time()+60*60*24*30; setcookie("user", "w3big", $expire); ?> <html> .....
In the example above, the expiration time is set to one month(60 seconds * 60 minutes * 24 hours * 30 days).
How to retrieve the value of the Cookie?
The PHP $ _COOKIE variable is used to retrieve a cookie value.
In the following example, we retrieve the value of the cookie named "user" and display it on the page:
<?php // 输出 cookie 值 echo $_COOKIE["user"]; // 查看所有 cookie print_r($_COOKIE); ?>
In the following example, we use the isset () function to verify that the set cookie:
<html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> <?php if (isset($_COOKIE["user"])) echo "欢迎 " . $_COOKIE["user"] . "!<br>"; else echo "普通访客!<br>"; ?> </body> </html>
How to Delete Cookie?
When you delete a cookie, so you should change the expiration date for the last time.
<?php // 设置 cookie 过期时间为过去 1 小时 setcookie("user", "", time()-3600); ?>
If your browser does not support Cookie how to do?
If your application needs to deal with do not support the browser cookie, you have to use other methods to pass information in your application between pages. One way is to pass data through forms (about forms and user input in the previous section of this tutorial we have been introduced).
The following forms in single user click "Submit" button to the "welcome.php" submit user input:
<html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> <form action="welcome.php" method="post"> 名字: <input type="text" name="name"> 年龄: <input type="text" name="age"> <input type="submit"> </form> </body> </html>
Retrieve "welcome.php" values in the file, as follows:
<html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> 欢迎 <?php echo $_POST["name"]; ?>.<br> 你 <?php echo $_POST["age"]; ?> 岁了。 </body> </html>