PHP learning-cookie and session

Source: Internet
Author: User
Tags http cookie php print set cookie

I recently read a bit of "PHP core technology and best practices", read cookies and sessions, and have some gains. Based on my previous understanding, I have read several blogs and summarized them ~~

1. PHP COOKIE

Cookie is a mechanism for storing data in a remote browser and tracking and identifying users.
PHP sends cookies in the http header. Therefore, the setcookie () function must be called before other information is output to the browser, which is similar to the header () function.

1.1 Set Cookie

You can use the setcookie () or setrawcookie () function to set the cookie. You can also set it by sending an http header directly to the client.

1.1.1   Use Setcookie () Function Set cookie

Bool setcookie (string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly])
Name: cookie name, that is, the key value of the Global Array $ _ COOKIE
Value: the value of the cookie variable. The parameter is null, And the Cookie value is null. A Cookie cannot save a boolean value. If the Cookie is applied, 0 indicates false, and 1 indicates true.
Expire: the end time of the validity period, in seconds.
Path: valid directory. The default value is "/", that is, the entire domain name is valid. If necessary, it can be set to only be valid in a directory.
Domain: Valid domain name, which is unique in the top-level domain. It is under the current domain name by default.
Secure: whether to encrypt the Cookie. The default value is false. If the value is true, the cookie can only be valid over https connections. If the default value is false, both http and https can be used.
Httponly: whether to only use HTTP to access cookies. If the value is 1 or true, the client's javascript cannot operate the Cookie. Using this parameter can reduce the risk of XSS attacks, but not all browsers support this parameter. This parameter is only valid for PHP5.2.0 and later versions.

Example:

<? = 'something from somewhere'("TestCookie", ); ("TestCookie", , ()+3600); ("TestCookie", , ()+3600, "/~rasmus/", ".example.com", 1); ?>

Set multiple cookie variables: setcookie ('var [a] ', 'value'); use an array to represent variables, but its subscript is not enclosed in quotation marks. In this way, you can use $ _ COOKIE ['var'] ['a'] to read the COOKIE variable.

The functions and parameters of setrawcookie are basically the same as those of setcookie. The only difference is that setrawcookie does not perform urlencode transcoding on values in the Cookie.

The Cookie set by PHP on the current page cannot take effect immediately. It can only be seen on the next page. If it is set by javascript, it will take effect immediately.

1.1.2. Use Header () Set cookie

Header ("Set-Cookie: name = $ value [; path = $ path [; domain = xxx.com [;...]");

The following parameters are the same as those listed in the setcookie function above.
For example:

<? = 'something from somewhere'("Set-Cookie:name="?>
1.2 Cookie reading

Directly use php's built-in Super global variable $ _ COOKIE to read the cookie on the browser.
The cookie is set in the preceding example."TestCookie", now we will read:

 ['TestCookie'];
1.3 Delete Cookie

Delete a Cookie that is not displayed. to delete a Cookie, set the Cookie expire to an expiration time, such as one hour ago and one month ago. This will automatically trigger the deletion mechanism of the browser, or set the value to null. For example:

("name","",()-1);

Similar to header.

1.4 Cookie cross-origin and P3P protocols

Normal cookies can only be shared by one application. That is, a Cookie can only be obtained by the application that created it. Cross-Domain Cookie implementation is to unify the application platform, that is, to achieve the popular single-point login. The simplest way is to use the P3P protocol.

Developed by the World Wide Web Association, P3P provides Web users with more control over their own public information. Websites that support P3P can declare their privacy policies for viewers. The browser that supports P3P can compare the Web site policy with the user's privacy preferences and give the user a non-matching warning. Therefore, users can be notified about how to handle Web privacy.

First, we will introduce the first-party Cookie and third-party cookie:

The first Cookie is from the website currently being viewed or sent to the website currently being viewed.

A third-party Cookie is sent from a website other than the currently viewed website or to a website other than the currently viewed website. Third-party websites generally provide content on the websites being viewed. For example, many websites use advertisements from third-party websites or URLs of iframe websites, which may use cookies.

Add the P3P header to a third-party webpage. If you want the browser to send the P3P protocol, you can solve the COOKIE sharing problem as follows:

("P3P","CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM CNT PRE LOC\"");
1.5 troubleshooting

1) An error message is prompted when setcookie () is used, probably because there is an output or space before setcookie () is called. Alternatively, your document may be converted from other character sets. The document may be followed by a BOM signature (that is, add some hidden BOM characters to the file content ). The solution is to prevent this problem from occurring in your documents. You can also use the ob_start () function to handle this problem. 2) $ _ COOKIE is affected by magic_quotes_gpc and may be automatically escaped. 3) when using it, it is necessary to test whether the user supports cookies. <! -- [If! SupportLineBreakNewLine] -->

Cookie 1.6 Working mechanism

A) the server sends an http Set-Cookie header in response and sets a cookie in the client (multiple cookies require multiple heads ).
B) The client automatically sends an http cookie header to the server, and the server receives and reads the cookie.

HTTP/1.x 200 OK
X-Powered-By: PHP/5.2.1
Set-Cookie:TestCookie=something from somewhere; Path =/
Expires: Thu, 19 Nov 2007 18:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check = 0, pre-check = 0
Pragma: no-cache
Content-type: text/html

This line implements the cookie function. After receiving this line
Set-Cookie:TestCookie=something from somewhere; Path =/
The browser will create a cookie file on the disk of the client, and write:

TestCookie=something from somewhere;
/

This line is what we usesetcookie('TestCookie','something from somewhere','/');. That is, useheader('Set-Cookie: TestCookie=something from somewhere; path=/');.

2. PHP Of Session

The session uses a cookie with the expiration time set to 0, and uses a unique identifier (a long string) called the session ID ), generate some session files synchronously on the server side (you can define the session storage type by yourself) and associate them with the user machine. Web applications store data related to these sessions, and transmit data between pages as users.

Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL.

Session support allows users to register any number of variables and keep them for use by each request. When visitors visit the website, PHP will automatically (if session. auto_start is set to 1) or when a user request (explicitly called by session_start () or secretly called by session_register () checks whether a specific session ID is sent in the request. If yes, the previously saved environment is rebuilt.

2.1 sessionID Transfer 2.1.1 Pass Cookie Transfer Sessin ID

Use session_start () to call the session. When the server generates the session file, it generates the session ID hash value and the session name with the default value PHPSESSID, and sends the variable (default) to the client) PHPSESSID (session name), with a 128-bit hash value. The server uses this cookie to interact with the client.
The session variable value is serialized in php and stored in a text file on the server. It interacts with the coolie whose client variable name is PHPSESSID by default.
That is, the server automatically sends the http header: header ('set-Cookie: session_name () = session_id (); path = /');
That is, setcookie (session_name (), session_id ());
After you jump to a new page from this page and call session_start (), PHP checks the session data stored on the server that is associated with the given ID. If no session data is found, a new dataset is created.

2.1.2PassURLTransferSession ID

This method is used only when the user disallows the use of cookies, because the browser cookie is already used. This method is not required for security purposes.
<A href = "p. php? <? Php print session_name ()?> = <? Php print session_id ()?> "> Xxx </a>, or pass the session value through POST.

2.2 Basic session usage example
<? 'Welcome to page #1'['favcolor'] = 'green'['animal'] = 'cat'['time'] =  '<br /><a href="page2.php">page 2</a>' '<br /><a href="page2.php?' . SID . '">page 2</a>'?><? ['animal']; (); ?>
2.3 use Session Function Control page Cache

Use session_cache_limiter ('private'); to control the page client cache, which must be called before session_start. Use session_cache_expire (int) to control the Client Cache Time. Unit: (s ). It must also be called before session_start. This is only a method for controlling the cache when session is used. We can also control the page cache in header.

2.4 delete a session

Three steps are required.

<?();                                      ((),'',()-3600);   = ();                                  ?>
2.5 session usage in PHP large-scale web Applications

The default session storage method is not suitable for websites with large traffic volumes. Currently, the optimal method is to access sessions using databases. At this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) is a solution to solve this problem.The function uses the following six functions:

1. bool open () is used to open the session storage mechanism.

2. bool close () closes the session storage operation.

3. This function is used when mixde read () is installed in session data from the storage.

4. bool write () writes all data of the given session ID to the storage.

5. bool destroy () destroys the data associated with the specified session ID.

6. bool gc () collects junk data in the storage system.

For example, see the session_set_save_handler () function in the php manual.
If the class is used for processing, use
Session_set_save_handler (
Array ('classname', 'open '),
Array ('classname', 'close '),
Array ('classname', 'read '),
Array ('classname', 'write '),
Array ('classname', 'deststroy '),
Array ('classname', 'gc '),
)
Call six static methods in the className class. ClassName can be used to change objects without calling static methods, but static members do not need to generate objects, which provides better performance.

The MEMORY engine can be used to store sessions in mysql database tables. The MEMORY engine uses MEMORY tables. All data is stored in the MEMORY and the operation speed is fast. This type of data is suitable for sessions, however, for websites with large traffic volumes, Session storage is inefficient and accounts for database connection resources. In this case, Key-Value data storage solutions such as Memcached and Redis can be used to achieve high-concurrency and high-traffic Session storage.

2.6 common Session Function

Bool session_start (void); initialize the session
Bool session_destroy (void): deletes the session associated files on the server.
String session_id () id of the current session
String session_name () indicates the name of the session currently accessed, that is, the cookie name used by the client to save the session ID. PHPSESSID is used by default.
Array session_get_cookie_params () details of the session associated with this session.
String session_cache_limiter () controls the client cache of pages using sessions
Ini session_cache_expire () controls the Client Cache Time
Bool session_destroy () deletes the file on the server that stores session information.
Void session_set_cookie_params (int lifetime [, string path [, string domain [, bool secure [, bool httponly]) sets session details associated with this session
Bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) defines the function for processing sessions (not by default)
Bool session_regenerate_id ([bool delete_old_session]) allocates a new session id

2.7 session Security Questions

By investing a lot of energy, attackers try to obtain valid session IDs of existing users. With session IDs, they may be able to have the same capabilities as this users in the system.
Therefore, our main solution is to verify the validity of the session ID.

<?(!(['user_agent'['user_agent'] = ['REMOTE_ADDR'].['HTTP_USER_AGENT' (['user_agent'] != ['REMOTE_ADDR'] . ['HTTP_USER_AGENT'?>

2.9 session instance
<?(!(['user_agent'['user_agent'] = (['REMOTE_ADDR'.['HTTP_USER_AGENT'     (['user_agent'] != (['REMOTE_ADDR'. ['HTTP_USER_AGENT'((),'',()-3600 = ?> 

Note:

The cause of the session header message being sent is the same as that of the cookie.
In php5, the Registry configuration options of all php sessions are configurable during programming. In general, we do not need to modify the configuration. For more information about php session registry configuration options, see Session session processing functions in the manual.

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.