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>
6. PHP会话控制:cookie和session区别与用法深入理解
9. JS读取PHP中设置的中文cookie时出现乱码怎么办
10. ThinkPHP6.0:Session和Cookie机制的变化
1. PHP中cookie怎么记录及删除变量?(图文+视频)
2. PHP cookie实现记录用户登陆信息的方法(图文+视频)