Home  >  Article  >  Backend Development  >  PHP cookie usage methods and precautions_PHP tutorial

PHP cookie usage methods and precautions_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:48:22851browse

Cookies are used to store information in the client browser. We can use cookies to record some relevant information about users. For example, the webmaster statistics code is implemented based on cookies and IP. Let me introduce the use of cookies and Things to note.

PHP cookie usage

The code is as follows Copy code
 代码如下 复制代码

setcookie('mycookie','value');
//函数原型:int setcookie(string name,string value,int expire,string path,string domain,int secure)
echo($mycookie);
echo($HTTP_COOKIE_VARS['mycookie']);
echo($_COOKIE['mycookie']);

setcookie('mycookie','value');

//Function prototype: int setcookie(string name,string value,int expire,string path,string domain,int secure)

echo($mycookie);

echo($HTTP_COOKIE_VARS['mycookie']);
echo($_COOKIE['mycookie']);

 代码如下 复制代码

setcookie('mycookie');或setcookie('mycookie','');或setcookie("mycookie",false);
//setcookie('mycookie','',time()-3600);
echo($HTTP_COOKIE_VARS['mycookie']);
print_r($_COOKIE);

Delete Cookies

(1) Call setcookie() with only name parameter;
 代码如下 复制代码

setcookie('mycookie','',time()-3600);

(2) Make the expiration time be time() or time-1;

The code is as follows Copy code


setcookie('mycookie'); or setcookie('mycookie',''); or setcookie("mycookie",false);

//setcookie('mycookie','',time()-3600);

echo($HTTP_COOKIE_VARS['mycookie']);
 代码如下 复制代码
$y2k = mktime(0,0,0,1,1,2000);
setcookie('name','value',$y2k);
setcookie('name', 'value', time+3600);
setcookie('name', 'value', $y2k, '~/myhome', '.domain.com');
print_r($_COOKIE);

Suggested deletion method:
The code is as follows Copy code
setcookie('mycookie','',time()-3600);
 代码如下 复制代码

$expire = time() + 86400; // 设置24小时的有效期
setcookie ("var_name", "var_value", $expire); // 设置一个名字为var_name的cookie,并制定了有效期
setcookie ("var_name_expire", $expire, $expire); // 再将过期时间设置进cookie以便你能够知道var_name的过期时间

PHP provides a very useful function mktime(). You just need to pass to mktime() the hours, minutes, seconds, months, dates, and years you want to represent in order, mktime() will return the total number of seconds since January 1, 1970. So if you need to simulate the Y2K problem:
The code is as follows Copy code
$y2k = mktime(0,0,0 ,1,1,2000); setcookie('name','value',$y2k); setcookie('name', 'value', time+3600); setcookie('name', 'value', $y2k, '~/myhome', '.domain.com');
How to get COOKIE expiration time
The code is as follows Copy code
$expire = time() + 86400; // Set the validity period of 24 hours setcookie ("var_name", "var_value", $expire); // Set a cookie named var_name and set the validity period setcookie ("var_name_expire", $expire, $expire); // Set the expiration time into the cookie so that you can know the expiration time of var_name

Note:

When sending a cookie, the cookie value is automatically URL-encoded. URL decoding occurs on reception.
If you don't need this, you can use setrawcookie() instead.

PHP setting, obtaining and deleting COOKIE

The code is as follows Copy code
 代码如下 复制代码

//--------设置COOKIE,1小时后过期------//
setcookie('TestCookie','hello word 秦迷',time()+3600);
//setrawcookie不进行URL编码
header('Content-type: text/html');
 

//查看发送的报头
var_dump(headers_list());#array(2) { [0]=> string(85) "Set-Cookie: TestCookie=hello+word+%C7%D8%C3%D4; expires=Tue, 19-Apr-2011 10:06:14 GMT" [1]=> string(23) "Content-type: text/html" }
echo '
';
echo $_COOKIE['TestCookie'];#hello word 秦迷
//兼容旧版本(淘汰)
if(isset($HTTP_COOKIE_VARS["TestCookie"])){
    echo $HTTP_COOKIE_VARS["TestCookie"];
}
 

echo '
';
//输出所有 cookie
print_r($_COOKIE);#Array ( [key] => value [TestCookie] => hello word 秦迷 )
?>
 


 

 

//-----设置数组COOKIE-------//
setcookie("cookie[one]","oneVal",time()+3600);
setcookie("cookie[two]","twoVal",time()+3600);
 

echo '
';
echo $_COOKIE['cookie']['two'];#twoVal
echo '
';
 

//输出 cookie (在重载页面后)
if (isset($_COOKIE["cookie"]))
{
    foreach ($_COOKIE["cookie"] as $name => $value)
    {
       echo "$name : $value
";
       /**
        * two : twoVal
        * one : oneVal
        */
 

    }
}
 

 

//设置过期,删除COOKIE
//setcookie('TestCookie', '', time() - 3600);
//setcookie('cookie[one]', '', time() - 3600);

//--------Set COOKIE and expire in 1 hour------// setcookie('TestCookie','hello word Qin Mi', time()+3600); //setrawcookie does not perform URL encoding header('Content-type: text/html'); //View the sent header var_dump(headers_list());#array(2) { [0]=> string(85) "Set-Cookie: TestCookie=hello+word+%C7%D8%C3%D4; expires=Tue, 19-Apr- 2011 10:06:14 GMT" [1]=> string(23) "Content-type: text/html" } echo '
'; echo $_COOKIE['TestCookie'];#hello word Qin Mi //Compatible with old versions (obsolete) if(isset($HTTP_COOKIE_VARS["TestCookie"])){ echo $HTTP_COOKIE_VARS["TestCookie"]; } echo '
'; //Output all cookies print_r($_COOKIE);#Array ( [key] => value [TestCookie] => hello word Qin Mi ) ?> '; echo $_COOKIE['cookie']['two'];#twoVal echo '
'; //Output cookie (after reloading the page) if (isset($_COOKIE["cookie"])) { foreach ($_COOKIE["cookie"] as $name => $value) { echo "$name : $value
"; /**         * two : twoVal         * one : oneVal        */ } } //Set expiration and delete COOKIE //setcookie('TestCookie', '', time() - 3600); //setcookie('cookie[one]', '', time() - 3600);


Method 1:

There are some restrictions on the use of cookies in PHP.
1. Use setcookie must be before the tag
2. Before using setcookie, you cannot use echo to input content
3. The cookie will not appear until the web page is loaded
4. setcookie must be placed before any data is output to the browser before sending

Due to the above limitations, when using the setcookie() function, you may encounter problems such as "Undefined index", "Cannot modify header information – headers already sent by"... etc. The solution is to generate a cookie before outputting the content. You can add the function ob_start();

at the top of the program

ob_start: Open the output buffer
Function format: void ob_start(void)
Note: When the buffer is activated, all non-file header information from the PHP program will not be sent, but will be saved in the internal buffer. In order to output the contents of the buffer, you can use ob_end_flush() or flush() to output the contents of the buffer.

Method 2:

Solution to Warning: Cannot modify header information – headers already sent by ……

A few days ago, I installed a php photo-tag system for testing, and found an error message Warning: Cannot modify header information – headers already sent by….I installed openads again today, and this problem still occurred. Angry. I searched online for a long time, and someone said that I should write ob_start(); at the beginning of the file, but the result failed. Later open php.ini and set output_buffering to on. Restart appache, OK. It seems this is the solution.

Special note: If you use utf-8 encoding, you must remove the BOM in UTF-8. This is because the utf-8 encoded file contains BOM, and php4 and 5 do not support BOM. To remove the BOM, you can open it with Notepad++ and convert it. Remember, remember, remember! (I struggled with this problem for a long time.)

Method three:

The currently set cookie does not take effect immediately, but will not be visible until the next page. This is due to the setting of this page
The cookie is passed from the server to the client's browser, and the browser can take the cookie out of the client's machine and send it back to the server on the next page
because. Setting cookies on the same page actually works from back to front, so if you want to delete a cookie before inserting a new one, you must
Write the insert statement first and then the delete statement, otherwise undesired results may occur.

When a COOKIE is deleted, the value of the COOKIE is still valid on the current page, that is, the value still exists, and it will not exist the next time the page or other pages are requested. In other words, PHP's COOKIE related operations are all asynchronous. When a COOKIE is set or deleted previously, it will not be correctly reflected until the next request.

It is best not to use the setcookie(cookie name) method when deleting COOKIE. This will easily delete the entire COOKIE array. I won’t go into details. Just pay attention. The best way to delete COOKIE is to set the effective time to the past. , when the browser finds that the COOKIE has expired, it will definitely send a delete COOKIE event. Another thing to note is that there are several parameters when setting the COOKIE, and there are also several parameters when deleting, otherwise it is easy to make mistakes.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632799.htmlTechArticleCookie is a cookie used to store information in the client browser. We can use cookies to record some relevant information about the user. Information, like the webmaster statistics code is implemented based on cookies and IP, below...
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