Simple PHP Session Description Introduction _php instance

Source: Internet
Author: User
Tags php language session id php session php script sessions unique id

Now the programmer is becoming more and more difficult, want to master, must seek to trace the source, this is in fact with the increasingly advanced language and a large number of frameworks is just the opposite, because they are as far as possible to conceal the origin to make it simple, personally called the programmer learning Paradox.

Note: The author is in touch with web development and PHP for about two weeks, the following content is suitable for beginners.

1, guide

From the text topic see,< simple PHP Conversation (session) Description > is already delineated the content scope of this article, trying to clarify the session (the text of the conversation referred to as sessions) in the PHP language is how to implement and use, focus on the basic understanding of the use.

The article idea is first to make clear what the session is, what the session has to use, session using the routine is what, PHP is how to use.

2. Conversation (session) description

Before beginning, first recommend a basic theory book "http authoritative guide", is the programmer basic Knowledge, the author has electronic version, there is a need to leave a message.

A. The origin of the session

Almost everyone online, hundreds of millions of data in the network transmission, the data can be safely transmitted, is based on the HTTP protocol, is very familiar with it. What the HTTP protocol does is to provide a series of methods for completing your network access, in which the two sides build a visit, in principle a session is established. To say an example: Xiaoming in the browser input https://www.baidu.com/(HTTPS is an encrypted version of HTTP, compared to the increase of SSL encryption layer), this is xiaoming to Baidu launched a request, said: "I want to see your interface," Baidu's server received information, The information includes a nickname want to do things, but also includes the address of xiaoming (otherwise Baidu does not know to whom the content to), the server check information OK, to xiaoming this request for the record, send a nickname want things, a complete request is over. This is a session, the core of the session is Xiaoming's information record (in fact, it also involves TCP/IP connectivity issues, this is irrelevant to this article, ignore).

In fact, rather than building a session, rather than a visit as a summary of the session.

B. What can be done in session

From the above content can be obtained, each access is a session, the server has to record information, this is the cost, at the same time, it is not likely that the same person to visit 10 times 20 times to build save 10 times 20 times, one is to increase the cost, the other is also more stupid. In other words, a person (exactly the same computer and browser), at a certain time, can reuse a session, why at a certain time? Because the session has a default expiration time, after the expiration of the server to clean up (if not so, you think about the world so many people, to a reservation, too deficient).

OK, since the same person, many visits are a session (do not suspect that the server can not be discriminated is the same person, specific to see the book recommended), and each visit to the content is to do the record, then that is, your session cycle in all the behavior of the server is aware of, Then the important role is coming, the server through the analysis of your access request, you can learn the specific user's behavior preferences, through a certain analysis, can push some users like to care about the data, advertising orientation is so.

Of course there may be other users, performance and so on, the individual is not particularly understanding the mechanism, here is the case.

3, the use of the session in PHP

Through the above long-winded, you can find that the session of the concept is actually on the server side occurred. PHP provides a series of configuration, functions, and so on, a good implementation of the session function. Session support in PHP is a way to save some data on concurrent access, so that you can build more custom programs to improve the attractiveness of your Web site. A visitor visiting your Web site will be assigned a unique ID, which is called the session ID. This ID can be stored in a cookie on the client side, or it can be passed through a URL. Session support allows you to save the data in the request in a $_session array. When a visitor visits your site, PHP will automatically check (if Session.auto_start is set to 1) or check (explicitly via session_start () or implicitly through Session_register ()). Whether the current session ID is a previously sent request creation. If this is the case, then the previously saved environment will be rebuilt.

A. Basic usage of Session in PHP

By assigning a unique session ID to each individual user, you can implement the ability to store data separately for different users. Sessions are often used to save and share information between multiple page requests. In general, the session ID is sent to the browser by means of a cookie, and the data in the conversation is retrieved by the session ID on the server side. If the request does not contain session ID information, then PHP creates a new one and assigns a new ID to the newly created sessions.

The session's workflow is simple. When you start a session, PHP tries to look up the sessions ID (usually through the session cookie) from the request, and if the request does not contain session ID information, PHP creates a new one. After the session begins, PHP sets the data in the sessions to the $_session variable. When PHP stops, it automatically reads the content in the $_session, serializes it, and sends it to the session Save manager for saving. By default, PHP uses the built-in file session Save Manager (files) to save the session. You can also modify the session save manager that you want to use by configuring the item Session.save_handler (php.ini). For the file session Save Manager, session sessions data is saved to the location specified by the configuration item session.save_path (configuration item in php.ini). You can start a session manually by calling the function Session_Start. If the configuration item Session.auto_start is set to 1, the session starts automatically when the request starts. After the PHP script completes, the session closes automatically. You can also close a session manually by calling the function Session_wirte_close ().

B. PHP session information is configured in php.ini

This part of the content is said to be because, do not explain the previous problem, the Ghost knows php.ini in the configuration is what thing. The above mentioned Session.save_handler and Session.save_path, these two are the configuration items in php.ini, this is not in detail, because the PHP manual is too detailed. The default mode for this article is files.

C. The session mechanism in PHP

Session_Start () is the beginning of the session mechanism, which determines whether the current $_cookie[session_name ()];session_name () returns the COOKIE key value of the saved session_id. If not, a session_id is generated and the generated session_id is passed to the client as a cookie. This is equivalent to performing the following cookie operation. Conversely, if there is a session_id =$_cookie[session_name], then go to Session.save_path designated folder to find the name ' Sess_ '. session_id () Files. The contents of the read file are deserialized and then placed in the $_session.

At the end of the session, either the sessions write operation is performed or the session_write_close () operation is performed manually.

There are generally three ways to destroy a session in the Code,    

1. Setcookie (Session_name (), session_id (), Time () -8000000,..); Perform before exiting login

2. Usset ($_session); This deletes all the $_session data, and when it is refreshed, a cookie comes in, but there is no data.

3. Session_destroy (); Delete $_session Delete session file and session_id

Appendix, refer to a piece of code on the network, as the end bar.

Call function Open ($save _path, $session _name) <span style= "White-space:pre" > </span>//session initialization { 
    Global $sess _save_path; 
    $sess _save_path= $save _path; 
   return (true); 
   Call function Close () {return (true) when closing. 
    function Read ($id) {global $sess _save_path; 
    $sess _file= "$sess _save_path/sess_$id"; 
   Return (String) @file_get_contents ($sess _file); 
 
    The Write Operation function writes ($id, $sess _data) {Global$sess_save_path Before the execution of the script is completed; 
    $sess _file= "$sess _save_path/sess_$id"; 
     if ($fp = @fopen ($sess _file, "W")) {$return =fwrite ($fp, $sess _data); 
     Fclose ($FP); 
    Return$return; 
    else {return (false); 
 
    } function Destroy ($id) {global $sess _save_path; 
    $sess _file= "$sess _save_path/sess_$id"; 
   Return (@unlink ($sess _file)); 
 
    } function GC ($maxlifetime) {global$sess_save_path; foreach (Glob ("$sess _SAVE_PATh/sess_* ") As$filename {if (Filemtime ($filename) + $maxlifetime <time ()) {@unlink ($filename); 
   } return true; }

Above this simple PHP conversation (session) description is a small series to share all the content, I hope to give you a reference, but also hope that we support the cloud habitat community.

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.