الكوكيز في PHP
- Previous Page تحميل ملفات PHP
- Next Page الجلسات في PHP
cookie 常用于识别用户。
什么是 Cookie?
cookie 常用于识别用户。cookie 是服务器留在用户计算机中的小文件。每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie。通过 PHP,您能够创建并取回 cookie 的值。
如何创建 cookie?
setcookie() 函数用于设置 cookie。
注释:setcookie() 函数必须位于 标签之前。
语法
setcookie(name, value, expire, path, domain);
例子
在下面的例子中,我们将创建名为 "user" 的 cookie,把为它赋值 "Alex Porter"。我们也规定了此 cookie 在一小时后过期:
<?php setcookie("user", "Alex Porter", time()+3600); ?> <html> <body> </body> </html>
注释:在发送 cookie 时,cookie 的值会自动进行 URL 编码,在取回时进行自动解码(为防止 URL 编码,请使用 setrawcookie() 取而代之)。
如何取回 Cookie 的值?
PHP 的 $_COOKIE 变量用于取回 cookie 的值。
在下面的例子中,我们取回了名为 "user" 的 cookie 的值,并把它显示在了页面上:
<?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>
在下面的例子中,我们使用 isset() 函数来确认是否已设置了 cookie:
<html> <body> <?php if (isset($_COOKIE[\"user\ echo "+\"مرحبًا "+ $_COOKIE[\"user\"] +\"!\"+<br />; else echo "+\"مرحبًا ضيفًا!\"+<br />; ?> </body> </html>
How to delete a cookie?
When deleting a cookie, you should change the expiration date to a past time point.
Example of deletion:
<?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
What to do if the browser does not support cookies?
What if your application involves browsers that do not support cookies? You will have to take other methods to pass information from one page to another in the application. One way is to pass data from the form (we have already introduced the content of forms and user input earlier in this tutorial).
The following form submits the user input to "welcome.php" when the user clicks the submit button:
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>
Retrieve the value from "welcome.php" like this:
<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
- Previous Page تحميل ملفات PHP
- Next Page الجلسات في PHP