PHP Learning--cookie and session_php tutorials

Source: Internet
Author: User
Tags http cookie php print setcookie
Recently read a little "PHP core technology and best practices," read the cookie and session, some harvest, combined with the previous understanding of a few blog, summed up ~ ~

1. PHP Cookies

A cookie is a mechanism for storing data on a remote browser to track and identify users.
PHP sends a cookie in the header of the HTTP protocol, so the Setcookie () function must be called before other information is exported to the browser, similar to the limit on the header () function.

1.1 setting cookies

You can use the Setcookie () or Setrawcookie () function to set the cookie. It can also be set by sending HTTP headers directly to the client.

1.1.1 Set a cookie using the setcookie () function

BOOL Setcookie (string name [, string value [, int expire [, String path [, string domain [, bool secure [, BOOL HttpOnly ]]]]]] )
The name of the Name:cookie, which is the key value of the $_cookie global array
The value of the Value:cookie variable, the parameter is empty, and the value of the cookie is empty. The cookie cannot hold a Boolean value, and applying 0 indicates that false,1 represents true.
Expire: The time, in seconds, at which the validity period ends.
Path: Valid directory, default to "/", that is, the entire domain name is valid. If necessary, you can set only valid in a directory.
Domain: Valid domain name, top-level domain unique, default in this domain name.
Secure: If the cookie is encrypted, the default is False. If the value is true, the cookie is valid only on HTTPS connections, and HTTP and HTTPS are available if the default value is False.
HttpOnly: Whether to use HTTP only to access cookies. If 1 or true, the client's JavaScript cannot manipulate cookies, and using this parameter can reduce the risk of XSS attacks, but not all browsers support this parameter. This parameter is valid only for versions above PHP5.2.0.


  < span="">=  < span="">  < span="">  < span="">  ' Something from somewhere < span=""> '  < span="">< span="">< span="">< span="">< span=""> < span="">< span="">< span="">< span="">< span="">< span="">< < span="">c34>?>< span="">< span="">

Set multiple cookie variables: Setcookie (' var[a] ', ' value '), use an array to represent the variable, but his subscript is not quoted. This allows you to use $_cookie[' var ' [' a '] to read the COOKIE variable.

The functions and parameters of Setrawcookie are basically the same as Setcookie, except that Setrawcookie does not urlencode transcode the value in the cookie.

PHP settings on the current page of the cookie is not immediately effective, to wait until the next page to see, if it is set by JavaScript, is effective immediately.

1.1.2. Setting Cookies with header ()

Header ("Set-cookie:name= $value [;p ath= $path [;d[; ...]];

The following parameters are the same as those listed above for the Setcookie function.
Like what:

  < span="">= ' Something from somewhere '< span="">< span="">("set-cookie:name=< span="">"  < span=""> ?>

1.2 The reading of cookies

The browser-side cookie can be read directly with PHP's built-in Super global variable $_cookie.
Cookies are set in the example above"TestCookie",现在我们来读取:

< span="">< span="">[' TestCookie '];

1.3 Delete Cookies

Cookies do not appear to be deleted, if you want to delete cookies, the expire of the cookie should be set to expire, such as one hours ago, 1970, this time automatically trigger the browser's deletion mechanism, or set the value to null. For example:

< span="">("Name", "",< span="">()-1);

Similar to the header ().

1.4 Cookie Cross-domain and P3P protocol

A normal cookie can only be shared in one app, meaning that a cookie can only be obtained by the app that created it. The cross-domain of cookies is implemented to unify the application platform, that is, to achieve the current single sign-on. 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. Web sites that support P3P can declare their privacy policies for visitors. Browsers that support P3P can compare the policies of the Web site to the user's privacy preferences and present a mismatch warning to the user. As a result, users can be notified about how Web privacy is handled.

First, first-party cookies and third-party cookies are introduced:

The first-party cookie is from the Web site you are currently viewing, or to the site you are currently viewing.

A third-party cookie is from a site other than the one currently being viewed, or to a site other than the one currently being viewed. Third-party sites typically provide content on the site being viewed. For example, many sites use advertisements from third-party websites, or URLs of other sites in the IFRAME, which may be used by these third-party websites.

In the third party's web page to add P3P header, want to send P3P protocol browser to solve the problem of cookie sharing, as follows

< span="">("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 Frequently Asked questions resolved

1) There is an error when using Setcookie (), possibly because there is an output or a space in front of the call Setcookie (). It may also be that your document is converted from another character set, and the document may be followed by a BOM signature (that is, adding some hidden BOM characters to the contents of the file). The solution is to keep your documents from happening. There is also the ability to handle a point by using the Ob_start () function.
2) $_cookie affected by MAGIC_QUOTES_GPC, may be automatically escaped
3) When using, it is necessary to test whether the user supports cookies

1.6 Cookies working mechanism

A) The server sets a cookie (more than one cookie) in the client computer by sending an HTTP Set-cookie header in response.
b) The client automatically sends an HTTP cookie header to the server and the server receives the read.

http/1.x OK
Set-cookie: TestCookie = something from somewhere ; path=/
Expires:thu, 18:52:00 GMT
Cache-control:no-store, No-cache, Must-revalidate, post-check=0, pre-check=0

This line implements the cookie function, after receiving this row
Set-cookie: TestCookie = something from somewhere ; path=/
The browser creates a cookie file on the client's disk and writes it inside:

TestCookie=something from somewhere;

This line is setcookie('TestCookie','something from somewhere','/'); the result of our use. header('Set-Cookie: TestCookie=something from somewhere; path=/');that is the result of the use.

2. the Session of PHP

The session uses a cookie that has an expiration time of 0, and a unique identifier called the session ID (a long string of strings), which in the server-side synchronization generates some session files (which can define the save type of the session itself), linked to the user's office. The Web application stores the data associated with these sessions, and lets the data pass along with the user across the page.

Visitors to the site are assigned a unique identifier, the so-called session ID. It is either stored on the client's cookie or passed through the URL.

Session support allows users to register any number of variables and keep them for use by individual requests. When a visitor visits a website, PHP automatically (if Session.auto_start is set to 1) or when the user requests (explicitly called by session_start () or Session_register () secretly calls) checks whether a specific session ID is sent in the request. If it is, the previously saved environment is rebuilt.

2.1 SessionID the transmission

2.1.1 through Cookies Transfer Sessin ID

Using Session_Start () Call session, the server side generates session ID hash value and the default value is PHPSESSID session name, and sends the variable to the client (default). PHPSESSID (session name), the value is a 128-bit hash value. The server side will interact with the client through this cookie.
The value of the session variable is stored in a text file on the server machine after the internal serialization of PHP, and the client's variable name is PHPSESSID by default for the coolie of the corresponding interaction.
That is, the server automatically sends an HTTP header: header (' Set-cookie:session_name () =session_id (); path=/');
namely Setcookie (Session_name (), session_id ());
When a new page jumps from the page and calls Session_Start (), PHP checks the session data for the server-side storage associated with the given ID, and creates a new dataset if it is not found.

2.1.2 through URL Transfer Session ID

This method is only used when the user prohibits the use of cookies, as browser cookies are already common and are not available for security purposes.
= ">xxx, you can also pass the session value via post."

2.2 Session Basic Usage example

 ' Welcome to page #1 '[' favcolor '] = ' green '[' animal '] = ' cat ' 
               [' time ' =  ' 
Page 2 ' '
Page 2 ' < Span *< span> ?>!--? [' animal ']; (); ?>

2.3 Use Session function Controls Page caching

< span="">Use Session_cache_limiter (' private '); You can control the page client cache and must be called before Session_Start (). Controls the client cache time with session_cache_expire (int), unit (s). Also to be called before Session_Start (). This is just a way to control the cache using the session, and we can also control the cache of the control page in the header ().

2.4 Delete Session

Three steps to achieve

  < span="">();                                      < span="">< span="">< span="">(< span="">(),'',< span=""> < span="">< span="">< span="">< span="">< span=""> < span=""> ?>

The use of 2.5 session in PHP large Web applications

For sites with large access, the default session storage method is not suitable, the current optimal method is to use the database access session. At this point, the function bool Session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, CALLB ACK GC) is the solution that gives us the solution to this problem.
The 6 functions used by the function are as follows:

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

2. BOOL Close () closes the session store operation.

3. Mixde read () uses this function when loading session data from storage.

4. BOOL Write () writes all data for the given session ID to the store.

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

6. BOOL GC () garbage collects data from the storage system.

See the PHP manual Session_set_save_handler () function for examples.
If you use a class to process, use the
Session_set_save_handler (
Array (' ClassName ', ' open '),
Array (' ClassName ', ' close '),
Array (' ClassName ', ' read '),
Array (' ClassName ', ' write '),
Array (' ClassName ', ' destroy '),
Array (' ClassName ', ' GC '),
Call 6 static methods in the ClassName class. ClassName can change objects without invoking static methods, but using static members does not produce objects, which is better performance.

Session into the MySQL database table can use memory engine, memories engine using the table, all the data stored in memory, operation Speed, for the session of this form of data just right, but in the large flow of the site, the session storage is inefficient, Accounting for database connection resources and so on. In this case, high-concurrency, large-traffic session storage can be achieved using key-value data storage schemes such as memcached and Redis.

2.6 Common Session function

BOOL Session_Start (void); Initialize session
BOOL Session_destroy (void): Deletes the server-side session Association file.
String session_id () ID of the current session
String Session_name () the name of the session currently accessed, which is the cookie name where the client holds the session ID. Default PHPSESSID.
Array Session_get_cookie_params () the details of the session associated with this session.
String Session_cache_limiter () controls client-side caching of pages using session
INI session_cache_expire () controls client cache time
BOOL Session_destroy () Delete the server-side file that holds session information
void session_set_cookie_params (int lifetime [, String path [, string domain [, bool secure [, BOOL HttpOnly]]]) is set with this SE Details of the session associated with the Ssion
BOOL Session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, Callback G c) Define the function that handles the session (not by using the default method)
BOOL SESSION_REGENERATE_ID ([bool delete_old_session]) assigns a new session ID

2.7 Session Security Issues

By investing a lot of effort in trying to get the valid session ID of an existing user, with the session ID, they are likely to have the same capabilities as this user in the system.
Therefore, our main approach is to validate the validity of session ID.

  < span="">(!  < span="">  < span=""> ([' User_agent  ' < span="">  < span="">  < span=""> [' REMOTE_ADDR '].   < span=""> ['  http_user_agent ' < span="">  < span=""> < span=""> < span="">< span=""> (< span="">< span="">< span="">[' < span="">http_user_agent '< span="">?>< span="">

< strong="">< strong="">< strong="">< strong="">

< strong="">< strong="">< strong="">< strong="">< span="">

< strong="">< strong="">< strong="">< strong="">2.9 Session Usage Example

 (!([' User_agent '[' user_agent '] = ([' remote_addr '  .  [' Http_user_agent '     ([' user_agent ']! =  ( [' remote_addr '  . [' http_user_agent '    ( (), ',  () -3600   = ?>      

< strong="">< strong="">< strong="">< strong="">注明:

< strong="">< strong="">< strong="">< strong=""> session 出现头信息已经发出的原因与cookie一样.
在php5中,所有php session 的注册表配置选项都是编程时可配置的,一般情况下,我们是不用修改其配置的。要了解php的session注册表配置选项,请参考手册的Session 会话处理函数处。

< strong="">< strong="">< strong="">< strong=""> true techarticle recently read a little "PHP core technology and best practices," read the cookie and session, some harvest, combined with the previous understanding of a few blog, summed up ~ ~ 1.PHP Cookie Cook ...

  • < strong="">< strong="">< strong="">< strong="">
  • 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.