PHP session and cookie operations and usage

Source: Internet
Author: User
Tags define session set cookie

1. Cookie

1. PHP supports HTTP transparentlyCookie. Cookie is a mechanism for storing data in a remote browser and tracking and identifying users. AvailableSetcookie ()OrSetrawcookie ()Function to set the cookie. Cookie is HTTPHeader, soSetcookie ()The function must be called before other information is output to the browser.Header ()Function restrictions are similar. AvailableOutput buffer functionTo delay the output of the script until all cookies or other HTTPHeader.

Any cookie sent from the client will be likeGetAndPostThe data is automatically converted to a PHP variable.Register_globalsAndVariables_orderThe impact of the two configuration options. If you want to set multiple values for a cookie variable, add[]Symbol.

Automatic global variable array in PHP 4.1.0 and later versions$ _ CookieIt will always contain all cookie data sent from the client. In earlier versions of PHP, whenTrack_varsWhen the configuration option is enabled (this option is always enabled since PHP 4.0.3), the array variable set for cookie is$ Http_cookie_vars.

 

 

2 setcookie -- send a cookie

Description

BoolSetcookie(String name [, string value [, int expire [, string path [, string domain [, bool secure])

Setcookie ()Define a cookie sent together with other HTTP headers. Like other headers, cookies must be output in any other part of the script.BeforeSend (this is a protocol restriction ). This requires that the call of this function be placed before any output, including<HTML>And<Head>Label and any space. IfSetcookie ()If there is any output before, this function will fail and returnFalse. IfSetcookie ()If the function runs successfullyTrue. This does not indicate whether the user has accepted the cookie.

Note:Since PHP 4, you can use the output cache to output the content before calling this function. The cost is to cache all the output to the browser on the server until the following command sends them. Can be used in codeOb_start ()AndOb_end_flush ()To implement such a function, or by modifyingPHP. iniInOutput_bufferingYou can also modify the server configuration file.

BesidesNameAll other parameters are optional. You can use an empty string ("") To skip this parameter. Because the ParameterExpireIt is an integer. It cannot be dropped by a Null String. It can be zero (0. The following tableSetcookie ()Every parameter is explained.

 

Parameters Description Example
Name Cookie name Use$ _ Cookie ['cookiename']Call the cookie named cookiename.
Value Cookie value. This value is stored on the client and cannot be used to save sensitive data. Assume thatNameIs 'cookiename', you can use$ _ Cookie ['cookiename']Obtain the value.
Expire Cookie expiration time. This is a UNIX timestamp. Generally, the time () function and the number of seconds are used to set the cookie expiration time. Or mktime () is used to implement Time () + 60*60*24*30The cookie is set to expire after 30 days. If not set, the cookie will expire after the session ends (usually closed by the browser.
Path Valid Cookie Path on the server If this parameter is set'/'Then, the cookie isDomainIs valid. If it is set'/Foo /'The cookie isDomainUnder/Foo/Directory and Its subdirectories are valid, such/Foo/BAR/. The default value is the current directory of the cookie.
Domain Valid Domain Name of the cookie This parameter should be set'.Example.com'. Although.Not required, but it will be compatible with more browsers. If this parameter is setWww.example.comInWWWValid in the subdomain. For details, seeCookie SpecificationIn.
Secure Indicates whether the cookie is transmitted only through a secure HTTPS connection. When setTrueThe cookie is only set in secure connections. The default value isFalse. 0 or 1

 

3. Specific operations

 

A,Set COOKIE:

Setcookie ("mycookie", "value of mycookie ");
With expiration time:
Setcookie ("withexpire", "expire in 1 hour", time () + 3600); // 3600 seconds = 1 hour
Everything:
Setcookie ("fullcookie", "full cookie value", time () + 3600, "/Forum", ".phpuser.com", 1 );

B. Output COOKIE:

Echo $ mycookie;
Echo $ cookiearray [0];
Echo count ($ cookiearray );
Echo $ http_cookie_vars ["mycookie"];
Echo $ _ cookie ['mycooker'];

C,Delete COOKIE:

To delete a cookie, you must ensure that its expiration time is in the past to trigger the deletion mechanism of the browser.

Setcookie ("testcookie", "", time ()-3600 ,"/~ Rasmus/",". utoronto. ca ", 1 );

 

4. Common Defects:

  • Cookies do not take effect on the page on which they are set. to test whether a cookie is successfully set, you can access its value through another page before it expires. The expiration time is based on parameters.Expire. Easy to usePrint_r ($ _ cookie );To debug existing cookies.

  • The cookie can be deleted only when the same parameter is set and used. If its value is an empty string, orFalseAnd other parameters are the same as the previous setcookie call. The cookie with the specified name will be deleted on the remote client.

  • Because the cookie value is setFalseWill make the client try to delete this cookie, so save it on the cookieTrueOrFalseInstead of using a Boolean value0To indicateFalse, Use1To indicateTrue

  • You can set the cookie name to an array, but the values of each element in the array cookie will be exclusive to the user's system. Consider usingExplode ()The function uses multiple names and values to set a cookie. We do not recommendSerialize ()For this purpose, because it may cause a security vulnerability.

Ii. Session

1 session principle:

The session is stored on the server side (the session is stored as a file by default). The user's file is obtained based on the session ID provided by the client and the variable value is obtained, the session ID can use the cookie of the client or the QUERY_STRING of the http1.1 protocol (that is, the "?" And then the server reads the session directory ....... That is to say, session ID is used to obtain the ID card of the session variable stored in the service. When the code session_start (); is run, a session file is generated on the server, and a session ID corresponding to it is also generated, define session variables to be stored in the generated session file in a certain form. The session ID can be used to retrieve the Defined variables. After a cross-page session, you must execute session_start (); a session file is generated, and the corresponding session ID is generated, this session ID cannot be used to retrieve the variables in the first session file mentioned above, because this session ID is not the "key" to open it ". If the code session_id ($ session ID) is added before session_start (); no new session file is generated and the session file corresponding to this ID is directly read.
By default, the session in PHP uses the cookie of the client to save the session ID. Therefore, when the cookie of the client fails, the session will be affected. It must be noted that the session does not necessarily depend on the cookie, which is also a bit better than the cookie. When the cookie on the client is disabled or a problem occurs, PHP automatically attaches the session ID to the URL, so that the session variable can be used across pages through the session ID. However, this attachment also has certain conditions, that is, "session. use_trans_sid = 1 in PHP. ini or the -- enable-trans-Sid option is enabled during compilation ".

2 session operations:

 

2.1 session_start ():

Note: initialize a new session. If the client is already in the session, it will be connected to the original session.

 

2.2 session_destroy ():

Description: destroys the session variable.

 

2.3 session_name (STR ):

Description: sets or obtains the current session name. The session name is obtained without parameters.

Usage:

Set: session_name ("session name ");
Obtain: Echo session_name (); // The session name is output. If no value is set, the default PHPSESSID is output.

 

2.4 session_save_path ([path])

Note: It must be called before the session_start function.

If no parameter is set, the directory name of the current session is obtained.

If a parameter is set, the session is saved in a new directory.

 

2.5 session_id ([ID]):

Description: The session code is returned if any parameter is set.

If no parameter is set, the current session code is obtained.

If a parameter exists, the parameter is set to the code of the current session.

 

2.6 session_register (STR)

Note: Add a new variable to the current session.

Example: $ temp = "test session ";

Session_register ("Temp ");

 

2.7 session_unregister (STR)

Note: In the current session variable, delete the variable STR, which is permanently deleted.

 

2.8 session_is_registered (name)

Note: Check whether the name variable has been registered in the session.

 

2.9 session_encode ()

Returns a string containing the encoded current session data.

 

2.10 session_decode (data)

Description: decodes session data. If the session data is successful, the return value is true.

 

3. Set the session survival time

Note: The following two session_start () Execution locations

A,

Session_start ();

$ Life_time = 24*3600;

Setcookie (session_name (), session_id (), time () + $ life_time ,"/");

 

B,

$ Life_time = 24*3600;

Session_set_cookie_params ($ life_time );

Session_start ();

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.

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.