Front End Learning PHP conversation session

Source: Internet
Author: User
Tags session id php script setcookie

Previous words

Session technology is similar to a cookie and is used to store information about Users. The big difference, however, is that the cookie stores the data in the Client's computer, while the session stores the data under the server System. The Chinese meaning of the session is the conversation, in the Web system, usually refers to the user and the Web system dialogue process. This article will explain the contents of the session in detail

Session ID

In the history of Web technology, Although the advent of cookie technology is a significant change, but the cookie is in the client computer to save information, so it caused a controversy. The user has the right to block the use of cookies so that the Web server cannot track user information through Cookies. The session technology is to store user-related information in the server system, so users can not stop the use of the session

Session at the client only needs to save a session identifier created by the server for the user, called the session ID, and the value of the session variable is saved on the server side (file or database or memcache). Session ID is a string of 32-bit 16-digit numbers that are neither duplicated nor easily found.

The session ID is saved in the Client's cookie, and if the user blocks the use of the cookie, the session ID can be saved in the URL of the User's browser address bar. When the user requests the Web server, the session ID is sent to the server, and then the session ID is extracted from the server in the session Variable. The variables stored in the session can be considered as global variables for the user, and the same User's access to each script is Shared.

When a user makes a request to a Web server, the server first checks to see if a session ID is already included in the Client's Request. If included, indicates that the session was previously created for this user, and the server is retrieved by the session ID for Use. If the client request does not contain a session id, a session is created for the user, and a session ID associated with the session is generated, which is passed to the client in this response to save

"session_start ()"

When a user makes a request to a Web server, the Session_Start () function must first be used to start a new session or to reuse an existing one, and a successful start session returns true, which returns false

bool session_start ([array $options = []])

Because a cookie-based session is opened, calling the Session_Start () function generates a unique sessionid that needs to be stored in a cookie on the client computer, as in the Setcookie () Function. Cannot have any output before the call, a space or a blank line.

If you have already opened the session, calling the Session_Start () function again will not create a new session ID. Because when the user accesses the server again, the function returns a session that already exists by passing the session ID that comes from the Client. So during a session, the same user accesses any page on the server using the same session ID

Session_Start ();

also, using the Session_Start () method creates a session file (a text File) with the same name on the server Side.

If you do not want to use the Session_Start () function in each script to open the session, you can set the "session.auto_start=1" in php.ini, you do not need to call session_start every time before using the session ( function however, There are some restrictions on enabling this option, and you cannot put the object in the session because the class definition must be loaded before the session Starts. It is not recommended to use the Session.auto_start attribute in php.ini to open session

Read and write session

After the session is started using the Session_Start () method, the session is read and written by accessing the $_session array. Similar to $_post,$_get,$_cookie ,$_session is also a hyper-global array

Storing data in a SESSION file with the same name using the $_session array

<? PHP Session_Start (); $_session [' username '] = ' Huochai '; $_session [' Age '] =;? >

The session file with the same name can be opened directly using a text editor with the following content Structure:

Variable name | type: length: value;

<? PHP Session_Start (); Print_r ($_session); // Array ([username] = Huochai [age] =?>

The session variable is saved in a file on the server side, where the file is located through the php.ini file, under the directory specified by the Session.save_path property

Configure session

In PHP configuration file php.ini, There is a set of session-related configuration Options. By re-setting the new value for some options, you can configure the session or use the default session configuration

Phpinfo ();
Session.auto_start=0; Initializes the Sessionsession. cache_expire=180 when the request is started; sets the session document in the cache obsolete session after n minutes. Cookie_lifetime=0; Setting the cookie save time (s), which is equivalent to setting the session expiration time, is 0 until the browser isrestarted. cookie_path=/; Valid path to the cookie session. cookie_domain=; The valid domain of the cookie session. name=phpsessid; The name of the session used in the cookie session. save_handler=files; control method for saving/ retrieving data session. save_path=/tmp; in Save_ Handler the parameter to the controller when it is set to a file, which is the path to which the data file will be Saved. session. use_cookies=1; whether to use cookies

Destroy session

When you have finished using a session variable, you can delete it and destroy it when you have completed a Conversation. If the user wants to quit the web system, it needs to provide a logout function to destroy all the information on the Server. To destroy all the data related to the current session, you can call the Session_destroy () function to end the current session and empty all resources in the session

"session_destroy ()"

Session_destroy (void)    

Session_destroy () destroys all data in the current session, deletes the session file with the same name, but does not reset the global variables associated with the current session, nor resets the conversation cookie. If you need to use session variables again, You must recall the Session_Start () function

<? PHP Session_Start (); Session_destroy ();? >

You can use the unset () function to release a single variable registered in the session

Print_r ($_session); // ' Array ([username] = Huochai [age] = +) ' unset ($_session[' username ']); unset ($_session[' age ']); Print_r ($_session); // ' Array () '

[note] do not use unset ($_session) to delete the entire $_session array, so you can no longer register variables with the $_session hyper-global array.

If you want to delete all the variables that a user registers in the SESSION, you can assign the array variable $_session to an empty array directly

$_session=array();    

PHP default session is based on the cookie, the session ID is stored in the Client's cookie in the server, so in the logoff session also need to clear the cookie saved sessionid, and this must use Setcookie () function is Complete. In a cookie, the cookie identifying name that holds the session ID is the name of the session, which is the value specified by the Session.name property in Php.ini. In a PHP script, you can get the session name by calling the Session_name () Function. Delete the session ID saved in the client cookie

if (isset($_cookie[session_name(    ))) {setcookie(session_ Name(), ", time() -3600);}

The previous introduction can be summed up, the session of the logoff process requires a total of four steps

<?PHP//first Step: open session and initializeSession_Start();//the second step: delete all SESSION variables, can also be unset ($_session[xxx]) deleted one by one$_session=Array();//Step three: If you use a cookie-based session, use setcooike () to delete the cookie containing the session IDif(isset($_cookie[Session_name()])) {    Setcookie(Session_name(),‘‘, time()-42000);}//Fourth Step: finally completely destroy the session, delete the server side retention session information filesSession_destroy();?>

Automatic Recycling

If you do not destroy the session through the above steps, but instead directly close the browser, or off the network, etc., the session file saved on the server will not be Deleted. Because in the php.ini configuration file, The default session.cookie_lifetime=0 indicates that the session ID is valid for the client cookie until the browser is Closed. The session ID disappears, but the session file saved by the server is not Deleted. therefore, the server-side session file that is not associated with the session ID becomes garbage, and the system provides a mechanism for automatic cleanup.

The session file saved by the server is a normal text file with file modification Time. Set an expiration time by setting the Session.gc_maxlifetime option in the php.ini configuration file (default is 1440 seconds, or 24 minutes). The garbage collection program finds files in all session files that are larger than 24 minutes. If the user is still using the file, then the session file modification time will be updated, will not be detected

When excluded, the garbage is not cleaned up immediately, but is determined by the ratio of the session.gc_probability/session.gc_divisor values in the profile php.info to when the cleanup is made, the default value is 1/100. Indicates that the garbage collection mechanism may be started at one time to automatically recycle garbage after 100 troubleshooting. of course, This value can be modified, but also to take into account the performance of the server and storage space

Front End Learning PHP conversation session

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.