Home >Backend Development >PHP Tutorial >PHP cookie usage methods and precautions_PHP tutorial
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 | ||||
//Function prototype: int setcookie(string name,string value,int expire,string path,string domain,int secure) echo($mycookie);
echo($HTTP_COOKIE_VARS['mycookie']); |
代码如下 | 复制代码 |
setcookie('mycookie');或setcookie('mycookie','');或setcookie("mycookie",false); |
(1) Call setcookie() with only name parameter;
代码如下 | 复制代码 |
setcookie('mycookie','',time()-3600); |
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']);
|
The code is as follows | Copy code | ||||
setcookie('mycookie','',time()-3600);
|
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'); |
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 | ||||
'; 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 programob_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.