PHP cookie usage and precautions

Source: Internet
Author: User
Tags set cookie

Cookie is used to store information in the client browser. We can use cookies to record user-related information. For example, the webmaster's statistical code is implemented based on cookies and ip addresses, the following describes how to use and pay attention to cookies.

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 ',' ');

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


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 );
// -->


<? 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

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: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.