PHP cookie usage and precautions

Source: Internet
Author: User
Tags function prototype set cookie setcookie

PHP cookie usage

The code is as follows: Copy code

Setcookie ('mycooker', 'value ');
// Function prototype: int setcookie (string name, string value, int expire, string path, string domain, int secure)
Echo ($ mycookie );
Echo ($ HTTP_COOKIE_VARS ['mycooker']);
Echo ($ _ COOKIE ['mycooker']);

Delete Cookie

(1) Call setcookie () with only the name parameter ();
(2) set the expiration time to time () or time-1;

The code is as follows: Copy code

<? Php setcookie ('name');?>

Setcookie ('mycookier'); or setcookie ('mycookier', ''); or setcookie (" mycookie ", false );
// Setcookie ('mycooker', '', time ()-3600 );
Echo ($ HTTP_COOKIE_VARS ['mycooker']);
Print_r ($ _ COOKIE );

Recommended deletion methods:

The code is as follows: Copy code

Setcookie ('mycooker', '', time ()-3600 );

PHP provides a very useful function mktime ().
You only need to transmit it to mktime () in sequence, the hours, minutes, seconds, months, dates, and years you want to represent,
Mktime () returns the total number of seconds from January 1, January 1, 1970.

Therefore, if you need to simulate the Y2K problem:

The code is as follows: Copy code
$ Y2k = mktime );
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 24-hour validity period
Setcookie ("var_name", "var_value", $ expire); // set a cookie named var_name with a validity period
Setcookie ("var_name_expire", $ expire, $ expire); // Set the Expiration Time to 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 is performed when receiving the message.
If you do not need this, you can use setrawcookie () instead.

Set, retrieve, and delete cookies in PHP

 

The code is as follows: Copy code

// -------- Set COOKIE and expire in 1 hour ------//
Setcookie ('testcookie ', 'Hello word Qin fan', time () + 3600 );
// Setrawcookie does not undergo 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 '<br> ';
Echo $ _ COOKIE ['testcookie ']; # hello word Qin fan
// Compatible with the old version (obsolete)
If (isset ($ HTTP_COOKIE_VARS ["TestCookie"]) {
Echo $ HTTP_COOKIE_VARS ["TestCookie"];
}
 

Echo '<br> ';
// Output all cookies
Print_r ($ _ COOKIE); # Array ([key] => value [TestCookie] => hello word Qin fan)
?>
 

<Script type = "text/javascript">
<! --
Alert (document. cookie );
// -->
</Script>
 

 

<? Php
// ----- Set the array COOKIE -------//
Setcookie ("cookie [one]", "oneVal", time () + 3600 );
Setcookie ("cookie [two]", "twoVal", time () + 3600 );
 

Echo '<br> ';
Echo $ _ COOKIE ['cookies'] ['two']; # twoVal
Echo '<br> ';
 

// Output cookie (after reloading the page)
If (isset ($ _ COOKIE ["cookie"])
{
Foreach ($ _ COOKIE ["cookie"] as $ name => $ value)
    {
Echo "$ name: $ value <br> ";
/**
* 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 before the 2. You cannot use echo to input content before using setcookie.
3. The cookie will not appear until the webpage is loaded
4. setcookie is sent only when it is placed in any data output browser.

Due to the above restrictions, when using the setcookie () function, you will learn to encounter "Undefined index", "Cannot modify header information-headers already sent "... The solution is to generate a cookie before the output 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 zone is activated, all non-file header information from the PHP program is not sent, but stored in the internal buffer zone. To output the buffer content, you can use ob_end_flush () or flush () to output the buffer content.

Method 2:

Solve Warning: Cannot modify header information-headers already sent ......

A few days ago, I installed a php big head sticker system test and found the error Warning: Cannot modify header information-headers already sent .... This problem still occurs when openads is installed again today. Angry. After searching for the Internet for half a day, some people say they want to write ob_start (); at the beginning of the file, and the result fails. Then open php. ini and set output_buffering to on. Restart appache, OK. It seems that this is the solution.

Note: If you use UTF-8 encoding, you must remove the BOM in the UTF-8, this is because of the bom contained in the UTF-8 encoding file, and php4, 5 are not supported bom. Remove bom and use Notepad ++ to open the conversion. Remember, remember, remember! (This problem has plagued me for a long time .)

Method 3:

The currently set Cookie does not take effect immediately, but will not be visible until the next page. This is because
The Cookie is transmitted by the server to the client's browser. The browser on the next page can retrieve the Cookie from the client's machine and send it back to the original server.
Because. Setting a Cookie on the same page is actually going forward from the back. Therefore, if you want to delete a Cookie before inserting it, you must
Write the insert statement first and then the delete statement. Otherwise, unexpected 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. The value does not exist in the next request to the page or other pages. That is to say, PHP's COOKIE-related operations are asynchronous. If the current side sets or deletes the COOKIE, it will not be correctly reflected until the next request.

It is recommended that you do not use setcookie (COOKIE name) to delete a cookie. This makes it easy to delete the entire COOKIE array. I will not elaborate on it. Just pay attention to it, the best way to delete a COOKIE is to set the validity period to the past. When the browser finds that the COOKIE is valid, it will indeed delete the COOKIE. Note that there are several parameters when setting the COOKIE, there must also be several parameters to delete, otherwise it is prone to errors.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.