php cookie (topic)
This topic comprehensively introduces the origin of php cookie, what are the attributes of php cookie, the usage of php cookie function and the practical application examples of php cookie through pictures, texts and videos. It is easy to understand! Welcome students from php Chinese website to learn!
1: What is Cookie?
Cookies are often used to identify users.
A cookie is a small file that the server leaves on the user's computer.
Every time the same computer requests a page through a browser, the cookie will be sent by the computer.
With PHP, you can create and retrieve cookie values.
Relevant topic recommendations: php session
2: The birth of Cookie
Since the HTTP protocol is stateless, the server-side business must be stateful.
The original purpose of Cookie was to store status information in the web to facilitate server-side use.
For example, determine whether the user visits the website for the first time. The latest specification is RFC 6265, which is a specification implemented by browser servers working together.
3: Principle of Cookie
When you visit the website for the first time, browse The server sends a request. After the server responds to the request, it will put the cookie into the response request. When the browser sends the request for the second time, it will bring the cookie with it. The server will identify the user. Of course, the server can also modify the cookie content. .
Four: Cookie attributes
Cookie is a small text data of no more than 4KB, consisting of a name (Name), a Value (Value) and several other optional attributes used to control cookie validity, security, and usage scope.
Name | represents the name of the cookie. |
Value | represents the value of the cookie. |
Domain |
Specifies the Web site or domain that can access the cookie. The cookie mechanism does not follow the strict origin policy, allowing a subdomain to set or obtain the cookie of its parent domain. |
Path | defines the directory on the Web site where the cookie can be accessed. |
Expires | What is the validity period is the Expires attribute in the picture. Generally, browser cookies are stored by default. When browsing is closed When the server ends the session, the cookie will be deleted. |
Secure |
Specifies whether to use the HTTPS security protocol to send cookies. Using the HTTPS security protocol can protect cookies from being stolen and tampered with during transmission between the browser and the web server. This method can also be used for identity authentication of Web sites, that is, during the HTTPS connection establishment phase, the browser will check the validity of the SSL certificate of the Web site. |
HttpOnly | is used to prevent client scripts from accessing cookies through the document.cookie attribute, helping to protect cookies from being stolen or tampered with by cross-site scripting attacks. . |
5: PHP Cookie Function
1. setcookie - Send Cookie
setcookie ( string $name [, string $value = "" [, int $expire = 0 [, string $path = "" [, string $domain = "" [, bool $secure = false [, bool $httponly = false ]]]]]] ) : bool
setcookie() defines the cookie, which will be sent to the client together with the remaining HTTP headers.
Like other HTTP headers, the cookie must be sent before the script can produce any output (due to protocol restrictions).
Please call this function before producing any output (including and
or spaces).Once the cookie is set, you can use $_COOKIE to read it the next time you open the page.
Cookie value also exists in $_REQUEST.
Parameters
Parameters | Description |
name | Cookie name. |
value | Cookie value. This value is stored on the user's computer. Do not store sensitive information. |
expire | The expiration time of the cookie. This is a Unix timestamp, which is the number of seconds since the Unix epoch. In other words, you can basically use the result of the time() function plus the number of seconds you want to expire. |
path | Cookie Valid server path. When set to '/', the cookie is valid for the entire domain name domain. If set to '/foo/', the cookie is only valid for the /foo/ directory and its subdirectories in the domain. The default value is the current directory when the cookie is set. |
domain | Valid domain/subdomain name for the cookie. Set it as a subdomain name, which will make the cookie valid for this subdomain name and its third-level domain name. To make the cookie valid for the entire domain name, just set it to the domain name. |
secure | Set whether this cookie is only passed to the client through secure HTTPS connections. When set to TRUE, the cookie will only be set when a secure connection exists. If this requirement is handled on the server side, programmers need to only send such cookies over secure connections. |
httponly | Set to TRUE, the cookie can only be accessed through the HTTP protocol. This means that Cookie cannot be accessed through scripting languages such as JavaScript. To effectively reduce identity theft during XSS attacks, it is recommended to use this setting, but this statement is often controversial. |
返回值
如果在调用本函数以前就产生了输出,setcookie() 会调用失败并返回 FALSE。
如果 setcookie() 成功运行,返回 TRUE。
示例
<?php $value = 'something from somewhere'; setcookie("TestCookie", $value); setcookie("TestCookie", $value, time()+3600); /* 1 小时过期 */ setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1); ?>
2、setrawcookie — 发送未经 URL 编码的 cookie
setrawcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) : bool
setrawcookie() 和 setcookie() 非常相似,唯一不同之处是发送到浏览器的 cookie 值没有自动经过 URL 编码(urlencode)。
六:PHP Cookie 简单示例
1、基本操作
<?php //添加Cookie setcookie('username', 'phpcn', time() + 3600); //获取Cookie $username = $_COOKIE['username']; //删除Cookie setcookie('username', '', time() - 3600); //修改Cookie setcookie('username', 'phpcn-updated', time() + 3600); ?>
2、面向过程封装
<?php /** * 获取 Cookie * @param string $name Cookie 名称 * @return mixed Cookie 值 */ function cookie_get($name) { return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; } /** * 删除 Cookie * @param string $name Cookie 名称 */ function cookie_del($name) { setcookie($name, '', time() - 3600); } /** * 设置Cookie * @param string $name Cookie 名称 * @param mixed $value Cookie 值 * @param integer $expire Cookie 过期时间 * @param string $path Cookie 有效路径 * @param string $domian Cookie 有效域名/子域名 */ function cookie_set($name, $value, $expire = 3600, $path = '/', $domian = '') { setcookie($name, $value, time() + $expire); } /** * 检测 Cookie * @param string $name Cookie 名称 * @param boolean $has_empty 检测为空 * @return boolean */ function cookie_has($name) { return isset($_COOKIE[$name]); } ?>
3、面向对象封装
<?php class Cookie { const OPTION_EXPIRE = 'expire'; const OPTION_PATH = 'path'; const OPTION_DOMAIN = 'domain'; const OPTION_SECURE = 'secure'; const OPTION_HTTPONLY = 'httponly'; /** * Cookie 实例 * @var null */ private static $instance = null; /** * Cookie 选项 * @var array */ private $options = [ self::OPTION_EXPIRE => 3600, self::OPTION_PATH => '/', self::OPTION_DOMAIN => 'domain', self::OPTION_SECURE => false, self::OPTION_HTTPONLY => false ]; /** * Cookie constructor. * @param $options */ private function __construct($options) { $this->setOptions($options); } /** * privated __clone */ private function __clone() { } /** * 获取实例 * @param $options * @return Cookie|null */ public static function getInstance($options) { if (is_null(self::$instance)) { self::$instance = new self($options); } return self::$instance; } /** * 设置选项 * @param $name * @param $value */ public function setOption($name, $value) { if (isset($this->options[$name])) { $this->options[$name] = $value; } throw new InvalidArgumentException('Cookie option not exists:{$name}'); } /** * 设置多个选项 * @param $options */ public function setOptions($options) { foreach ($options as $name => $value) { $this->setOption($name, $value); } } /** * 设置 Cookie * @param $name * @param $value * @param array $options */ public function set($name, $value, $options = []) { $this->setOptions($options); if (is_array($value) || is_object($value)) { $value = json_encode($value); } setcookie( $name, $value, $this->options[self::OPTION_EXPIRE], $this->options[self::OPTION_PATH], $this->options[self::OPTION_DOMAIN], $this->options[self::OPTION_SECURE], $this->options[self::OPTION_HTTPONLY] ); } /** * 获取 Cookie * @param $name * @return array|mixed */ public function get($name) { $value = $_COOKIE[$name]; if (is_array($value)) { $arr=[]; foreach ($value as $k => $v) { $arr[$k] = substr($v, 0,1) == '{' ? json_decode($value) : $v; } return $arr; } else { return substr($value, 0,1) == '{' ? json_decode($value) : $value; } } /** * 删除 Cookie * @param $name * @param array $options */ public function del($name, $options = []) { $this->setOptions($options); $value = $_COOKIE[$name]; if ($value) { if (is_array($value)) { foreach ($value as $k => $v) { setcookie( $name . '[' . $k . ']', '', time() - 3600, $this->options[self::OPTION_EXPIRE], $this->options[self::OPTION_PATH], $this->options[self::OPTION_DOMAIN], $this->options[self::OPTION_SECURE], $this->options[self::OPTION_HTTPONLY] ); unset($v); } }else{ setcookie( $name, '', time() - 3600, $this->options[self::OPTION_EXPIRE], $this->options[self::OPTION_PATH], $this->options[self::OPTION_DOMAIN], $this->options[self::OPTION_SECURE], $this->options[self::OPTION_HTTPONLY] ); unset($value); } } } }
4、记住登录账号示例
<?php function cookie_get_username() { return isset($_COOKIE['username']) ? $_COOKIE['username'] : null; } function cookie_get_password() { return isset($_COOKIE['username']) ? $_COOKIE['username'] : null; } function cookie_get_remember() { return isset($_COOKIE['remember']) ? 'checked' : null; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username']; $password = $_POST['password']; if (isset($_POST['remember']) && $_POST['remember'] === '1') { setcookie('username', $username, time() + 3600); setcookie('password', $password, time() + 3600); setcookie('remember', '1', time() + 3600); } else { setcookie('username', '', time() - 3600); setcookie('password', '', time() - 3600); setcookie('remember', '', time() - 3600); } die('登录成功!'); } ?> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <form action="" method="post"> <table width="300" border="1" align="center" cellpadding="5" cellspacing="5"> <thead> <tr> <td colspan="2" align="center"><b>登录</b></td> </tr> </thead> <tr align="center"> <td>用 户 名</td> <td><input type="text" name="username" value="<?=cookie_get_username()?>"></td> </tr> <tr align="center"> <td>密码</td> <td><input type="password" name="password" value="<?=cookie_get_password()?>"></td> </tr> <tr align="center"> <td>记住账号</td> <td> <input type="checkbox" name="remember" value="1" <?=cookie_get_remember()?>> </td> </tr> <tr align="center"> <td colspan="2"><input type="submit" name="Submit" value="提交" /></td> </tr> </table> </form>
六:php cookie 精选技术文章
6. PHP会话控制:cookie和session区别与用法深入理解
9. JS读取PHP中设置的中文cookie时出现乱码怎么办
10. ThinkPHP6.0:Session和Cookie机制的变化
七:php cookie 相关视频教程
1. PHP中cookie怎么记录及删除变量?(图文+视频)
2. PHP cookie实现记录用户登陆信息的方法(图文+视频)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many Windows users have recently encountered an unusual error called Roblox403 Forbidden Error while trying to access website URLs in Google Chrome browser. Even after restarting the Chrome app multiple times, they were unable to do anything. There could be several potential causes for this error, some of which we've outlined and listed below. Browsing history and other cache of Chrome and corrupted data Unstable internet connection Incorrect website URLs Extensions installed from third-party sources After considering all the above aspects, we have come up with some fixes that can help users resolve this issue. If you encounter the same problem, check out the solutions in this article. Fix 1

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.

The dangers of cookie leakage include theft of personal identity information, tracking of personal online behavior, and account theft. Detailed introduction: 1. Personal identity information is stolen, such as name, email address, phone number, etc. This information may be used by criminals to carry out identity theft, fraud and other illegal activities; 2. Personal online behavior is tracked and analyzed through cookies With the data in the account, criminals can learn about the user's browsing history, shopping preferences, hobbies, etc.; 3. The account is stolen, bypassing login verification, directly accessing the user's account, etc.