Home >Backend Development >PHP Problem >How to update cookie content in php

How to update cookie content in php

(*-*)浩
(*-*)浩Original
2019-09-30 13:44:142759browse

The setcookie() function sends an HTTP cookie to the client.

How to update cookie content in php

A cookie is a variable sent by the server to the browser. Cookies are typically small text files that a server embeds on a user's computer.

This cookie is sent each time the computer requests a page through the browser. (Recommended learning: PHP video tutorial)

The name of the cookie is specified as a variable with the same name. For example, if the cookie being sent is named "name", a variable named $user is automatically created containing the cookie's value.

The cookie must be assigned before any other output is sent.

If successful, the function returns true, otherwise it returns false.

Today when I was doing exercises, I encountered the problem that the cookie in PHP must be refreshed to take effect. It can be solved by the following method:

//   php COOKIE设置函数立即生效,支持数组
 
function cookie($var, $value = '', $time = 0, $path = '', $domain = '', $s = false)
{
    $_COOKIE[var] = $value;
    if (is_array($value)) {
        foreach ($value as $k => $v) {
            setcookie($var .'['.$k.']', $v, $time, $path, $domain, $s);
        }
    } else {
            setcookie($var,$value, $time, $path, $domain, $s);
    }
}

In this way, there is no need to refresh, and the value of the cookie can be obtained directly. Yes, cookie parameter

Tip: In this code, these two sentences are effective for instant cookie update:

$_COOKIE[$var] = $value;
setcookie($var,$value,$time,$path,$domain,$s);

That is to say, the cookie is processed twice once Assignment.

The above is the detailed content of How to update cookie content in php. For more information, please follow other related articles on the PHP Chinese website!

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