Home  >  Article  >  php cookie (topic)

php cookie (topic)

PHPz
PHPzOriginal
2020-08-05 18:02:114321browse

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!

php cookie (topic)

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

php cookie (topic)

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.

php cookie (topic)

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 = &#39;something from somewhere&#39;;

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(&#39;username&#39;, &#39;phpcn&#39;, time() + 3600);

//获取Cookie
$username = $_COOKIE[&#39;username&#39;];

//删除Cookie
setcookie(&#39;username&#39;, &#39;&#39;, time() - 3600);

//修改Cookie
setcookie(&#39;username&#39;, &#39;phpcn-updated&#39;, 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, &#39;&#39;, 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 = &#39;/&#39;, $domian = &#39;&#39;)
{
	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 = &#39;expire&#39;;
    const OPTION_PATH = &#39;path&#39;;
    const OPTION_DOMAIN = &#39;domain&#39;;
    const OPTION_SECURE = &#39;secure&#39;;
    const OPTION_HTTPONLY = &#39;httponly&#39;;

    /**
     * Cookie 实例
     * @var null
     */
    private static $instance = null;

    /**
     * Cookie 选项
     * @var array
     */
    private $options = [
        self::OPTION_EXPIRE => 3600,
        self::OPTION_PATH => &#39;/&#39;,
        self::OPTION_DOMAIN => &#39;domain&#39;,
        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(&#39;Cookie option not exists:{$name}&#39;);
    }

    /**
     * 设置多个选项
     * @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) == &#39;{&#39; ? json_decode($value) : $v;
            }
            return $arr;
        } else {
            return substr($value, 0,1) == &#39;{&#39; ? 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 . &#39;[&#39; . $k . &#39;]&#39;,
                        &#39;&#39;,
                        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,
                    &#39;&#39;,
                    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[&#39;username&#39;]) ? $_COOKIE[&#39;username&#39;] : null;
}

function cookie_get_password()
{
    return isset($_COOKIE[&#39;username&#39;]) ? $_COOKIE[&#39;username&#39;] : null;
}

function cookie_get_remember()
{
    return isset($_COOKIE[&#39;remember&#39;]) ? &#39;checked&#39; : null;
}


if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {

    $username = $_POST[&#39;username&#39;];
    $password = $_POST[&#39;password&#39;];

    if (isset($_POST[&#39;remember&#39;]) && $_POST[&#39;remember&#39;] === &#39;1&#39;) {
        setcookie(&#39;username&#39;, $username, time() + 3600);
        setcookie(&#39;password&#39;, $password, time() + 3600);
        setcookie(&#39;remember&#39;, &#39;1&#39;, time() + 3600);
    } else {
        setcookie(&#39;username&#39;, &#39;&#39;, time() - 3600);
        setcookie(&#39;password&#39;, &#39;&#39;, time() - 3600);
        setcookie(&#39;remember&#39;, &#39;&#39;, time() - 3600);
    }

    die(&#39;登录成功!&#39;);
}

?>

<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 精选技术文章

1 .PHP7中创建COOKIE和销毁COOKIE的方法

2. 如何设置cookie和删除cookie

3. PHP 中 Session 和 Cookie 区别?

4. PHP 怎么带着 Cookie 跳转?

5. 注意!Laravel删除Cookie的小坑

6. PHP会话控制:cookie和session区别与用法深入理解

7. PHP之你不得不知道的COOKIE含义及使用方式

8. 怎样关闭阻止第三方cookie

9. JS读取PHP中设置的中文cookie时出现乱码怎么办

10. ThinkPHP6.0:Session和Cookie机制的变化

七:php cookie 相关视频教程

1. PHP中cookie怎么记录及删除变量?(图文+视频)

2. PHP cookie实现记录用户登陆信息的方法(图文+视频)

3. PHP cookie实现判断用户是否登录的方法(图文+视频)

4. PHP基于Cookie的购物车模块设计

5. 预定义变量(二):$_COOKIE浏览器上的小甜点

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn