PHP CookieLOGIN

PHP Cookie

PHP Cookie

Cookies are often used to identify users.

What are Cookies?

Cookie is generated by the server and sent to User-Agent (usually a browser). The browser will save the cookie key/value to a text file in a certain directory and request the same website next time. The cookie is sent to the server (provided the browser is set to enable cookies). Cookie names and values ​​can be defined by the server-side developer, so that the server can know whether the user is a legitimate user and whether he needs to log in again, etc. The server can set or read the information contained in Cookies to maintain the status of the user's session with the server.

How to create a cookie?

The setcookie() function is used to set cookies.

Note: The setcookie() function must be located before the <html> tag.

Syntax

setcookie(name, value, expire, path, domain);

Example 1

In the following example, we will create the name Be the cookie for "user" and assign it the value "runoob". We also specify that this cookie expires after one hour:

<?php
setcookie("user", "runoob", time()+3600);
?>
<html>
.....

Note: The cookie value is automatically URL-encoded when sending the cookie, and automatically decoded when retrieved. (To prevent URL encoding, use setrawcookie() instead.)

Example 2

You can also set the cookie expiration time in another way. This may be simpler than using seconds.

<?php
$expire=time()+60*60*24*30;
setcookie("user", "runoob", $expire);
?>
<html>
.....

In the above example, the expiration time is set to one month (60 seconds * 60 minutes * 24 hours * 30 days).

Cookie configuration and application

Setcookie(string name, string value, int expire,string path, string domain, intsecure); where name is the cookie variable name identifier. You can use it to reference the

cookie variable in PHP just like using an ordinary variable name. value is the initial value of the cookie variable, expire represents the validity time of the cookie variable; path represents the relevant path of the cookie variable; domain represents the website of the cookie variable; secure is valid only when https is securely transmitted.

SetCookie("Cookie", "cookievalue",time()+3600, "/forum", ".365shequ.com", 1);

Name, must be Value, must be milliseconds time()+3600=1 hour Save path Save domain HTTPS

PHP Read Cookie

Use the super global variable $_COOKIE array to read the current client Create a new PHP file set_cookie.php for the cookies saved in #Check whether the cookie has been set successfully


Set the expiration time for the cookie

The third parameter is the unix timestamp0 Default Value, it will expire when you close the browser

time() + 86400 one day

setcookie('foo', 'a', time() + 86400);

After setting Please close the browser, open the browser again and visit to check whether the cookie exists

Set the path for the cookie

setcookie('bar', 'b', time() + 86400, '/uploads');

• Please test whether the PHP page in the / directory can read the cookie named bar Cookie

•  Please test whether the Cookie named foo can be read in the PHP page under /uploads

•  Please create another subdirectory and test whether the PHP page in the subdirectory can Which cookies are read

Once the Path is set, the cookies under the Path can only be read by the page under the Path

is set for the Cookie Domain name

setcookie('key', 'val', time() + 86400, '/uploads', '.your.domain');

Set the domain to news. The cookie of php.cn cannot be read by the page under sports.365jia.cn, and vice versa

If you want all second-level domain names to share cookies, you need to set the domain to .php.cn

Cookie restriction issues

Many browsers have limits on the number of cookies. Most browsers stipulate the number of cookies that a website can set. The number cannot exceed 50, and some browsers even limit it to 30

Browsers also have restrictions on the size of cookies, which generally cannot exceed 4K size

Cookie Security Issues

If you do not shut down your computer after surfing the Internet in an Internet cafe, other people using your computer can view the history of all the websites you visit and the cookie content saved by the website. It is very dangerous if important data (user name, password, card number, mobile phone number, ID number...) is stored in cookies.

Therefore, important data cannot be stored in cookies. If it must be saved, it must rely on the server

Cookie Notes

Different computers cannot share it Cookie

Different browsers on the same computer cannot share Cookie

The same browser cannot share Cookie under different domain names

Even the same browser, Cookies with different paths under the same domain name cannot be shared

How to retrieve the value of Cookie?

PHP’s $_COOKIE variable is used to retrieve the value of the cookie.

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 isset() function to confirm whether the cookie has been set:

<html>
<head>
<meta charset="utf-8">
<title> php中文网(php.cn)</title>
</head>
<body>
<?php
if (isset($_COOKIE["user"]))
         echo "欢迎 " . $_COOKIE["user"] . "!<br>";
else
         echo "普通访客!<br>";
?>
</body>
</html>

How to delete cookies?

When deleting a cookie, you should change the expiration date to a point in time in the past.

Deleted example:

<?php
// 设置 cookie 过期时间为过去 1 小时
setcookie("user", "", time()-3600);
?>

What should I do if the browser does not support Cookies?

If your application needs to deal with browsers that do not support cookies, then you will have to use other methods to pass information between pages in your application. One way is to pass data through a form (forms and user input are covered in the previous chapters of this tutorial).

The following form submits user input to "welcome.php" when the user clicks the "Submit" button:

<html>
<head>
<meta charset="utf-8">
<title> php中文网(php.cn)</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 the value in the "welcome.php" file, as shown below:

<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
欢迎 <?php echo $_POST["name"]; ?>.<br>
你 <?php echo $_POST["age"]; ?> 岁了。
</body>
</html>

Half a beat

A mistake often made in actual development is to obtain data directly through $_COOKIE after setcookie

setcookie('foo', 1);

print_r($_COOKIE);
echo $_COOKIE['foo'];

In the above case, it is impossible Obtaining the cookie just set is the problem mentioned in our title.

The principle is very simple. Cookies are actually saved to the browser in the end. Only After the current page is returned to the browser, the value of setcookie will be saved in the browser. When the page is visited for the second time, PHP can read the data in the browser's Cookie

And $_COOKIE The data is brought from the client to the server every time the page is requested.

This is why it was set at the time and could not be retrieved at the time.

One way to solve the problem of half a beat is to save the data. The program refreshes the page immediately after the value.


Next Section
<?php // 设置 cookie 过期时间为过去 1 小时 setcookie("user", "", time()-3600); ?>
submitReset Code
ChapterCourseware