Analysis of PHP Session usage

Source: Internet
Author: User
Tags php session

The Session is stored on the server as a text file, so the client is not afraid to modify the Session content. In fact, in the Session file on the server side, PHP automatically modifies the Session file permissions, only retaining the system read and write permissions, and cannot be modified through ftp, which is much safer.

For Cookie, if we want to verify whether the user logs in, we must save the user name and password (which may be the md5 encrypted string) in the Cookie and perform verification on each request page. If the user name and password are stored in the database, a database query is executed every time, causing extra burden on the database. Because we cannot perform only one verification. Why? Because the information in the client Cookie may be modified. If you store the $ admin variable to indicate whether the user has logged on, $ admin indicates logging on when it is set to true, and false indicates not logging on, after the first verification is passed, $ admin equals true is stored in the Cookie, so no verification is required next time. Is this correct? Wrong. If someone spoofs a $ admin variable with the value true, isn't the administrator privilege immediately obtained? Very insecure.

The PHP Session is different. The Session is stored on the server, and remote users cannot modify the content of the Session file. Therefore, we can simply store a $ admin variable to determine whether to log on, after the first verification is passed, set $ admin to true, and then judge whether the value is true. If not, transfer it to the login interface, which can reduce a lot of database operations. In addition, it can reduce the security of passing passwords to verify cookies every time (Session verification only needs to be passed once, if you do not use the SSL Security Protocol ). Even if the password is encrypted with md5, it is easily intercepted.

Of course, Session has many advantages, such as easy control and user-defined storage (stored in the database ). I will not talk about it here.

Does PHP Session need to be set in php. ini? Generally, this is not required because not everyone has modified php. ini permission. The default Session storage path is the temporary system folder of the server. We can customize it to be stored in our own folder. I will introduce it later.

This topic describes how to create a Session. Very simple, really.

Start the Session and create a $ admin variable:

 
 
  1. // Start the Session
  2. Session_start ();
  3. // Declare a variable named admin and assign a null value.
  4. $ _ SESSION ["admin"] = null;
  5. ?> 

If you use Seesion or the PHP file needs to call the Session variable, you must start it before calling the PHP Session and use the session_start () function. PHP automatically creates the Session file.

After executing this program, we can find the Session file in the temporary folder of the system. The file name is generally sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-bit encoded random string. Open it in the editor and check its content:

Admin | N;

Generally, the content is structured as follows:

Variable name | type: Length: value;

Separate each variable with a semicolon. Some can be omitted, such as length and type.

Let's take a look at the verification program. Assume that the database stores the user name and the md5 encrypted password:

 
 
  1. Login. php
  2.  
  3. // After the form is submitted...
  4. $Posts=$ _ POST;
  5. // Clear some blank symbols
  6. Foreach ($ posts as $Key=>$ Value)
  7. {
  8. $ Posts [$ key] = trim ($ value );
  9. }
  10. $Password=Md5($ Posts ["password"]);
  11. $Username= $ Posts ["username"];
  12.  
  13. $Query="SELECT 'username' FROM 'user' WHERE 'Password' = '$ password '";
  14. // Obtain the query result
  15. $UserInfo= $ DB->GetRow ($ query );
  16.  
  17. If (! Empty ($ userInfo ))
  18. {
  19. If ($ userInfo ["username"] = $ username)
  20. {
  21. // After the verification is passed, start the PHP Session
  22. Session_start ();
  23. // Register the logon admin variable and assign the value true.
  24. $ _ SESSION ["admin"] = true;
  25. }
  26. Else
  27. {
  28. Die ("incorrect user name and password ");
  29. }
  30. }
  31. Else
  32. {
  33. Die ("incorrect user name and password ");
  34. }
  35.  
  36. ?> 

We start the Session on the page that requires user verification to determine whether to log on:

 
 
  1. // Prevent security risks caused by global variables
  2. $Admin=False;
  3.  
  4. // Start the session. This step is required.
  5. Session_start ();
  6.  
  7. // Determine whether to log on
  8. If (isset ($ _ SESSION ["admin"]) & $ _ SESSION ["admin"] = true)
  9. {
  10. Echo "you have successfully logged on ";
  11. }
  12. Else
  13. {
  14. // Verification Failed. Set $ _ SESSION ["admin"] to false
  15. $ _ SESSION ["admin"] = false;
  16. Die ("You are not authorized to access ");
  17. }
  18.  
  19. ?> 

Is it easy? Consider $ _ SESSION as an array stored on the server. Every variable we register is an array key, which is no different from the array used.

What if I want to log out of the system? Destroy the PHP Session.

 
 
  1. Session_start ();
  2. // This method destroys a previously registered variable.
  3. Unset ($ _ SESSION ["admin"]);
  4.  
  5. // This method destroys the entire Session file.
  6. Session_destroy ();
  7.  
  8. ?> 

Can a Session set a lifecycle like a Cookie? Does Session discard cookies? I would like to say that using Session with cookies is the most convenient.

How does the Session determine the client user? It is determined by the Session ID. What is the Session ID is the name of the Session file, and the Session ID is randomly generated. Therefore, the uniqueness and randomness can be ensured to ensure the security of the Session. Generally, if the Session life cycle is not set, the Session ID is stored in the memory. When the browser is closed, the ID is automatically deregistered. After the page is requested again, a Session ID is re-registered.

If the client does not disable the Cookie, the Cookie plays the role of storing the Session ID and Session lifetime when starting the PHP Session.

Let's manually set the Session lifetime:

 
 
  1. Session_start ();
  2. // Save for one day
  3. $LifeTime=24* 3600;
  4. Setcookie (session_name (), session_id (), time () + $ lifeTime ,"/");
  5.  
  6. ?> 

In fact, the Session also provides a function session_set_cookie_params (); To set the Session lifetime. This function must be called before the session_start () function is called:

 
 
  1. // Save for one day
  2. $LifeTime=24* 3600;
  3. Session_set_cookie_params ($ lifeTime );
  4. Session_start ();
  5. $ _ SESSION ["admin"] = true;
  6.  
  7. ?> 

If the client uses IE 6.0, session_set_cookie_params (); the function sets the Cookie. Therefore, we need to manually call the setcookie function to create the cookie.

What if the client disables cookies? No way. All life cycles are browser processes. You only need to close the browser and request the page to register the PHP Session again. So how to pass the Session ID? By passing through a URL or by hiding a form, PHP will automatically send the Session ID to the URL, the URL is like: http://www.openphp.cn/index.php? ... E5b44cfa01d49cf9669. the PHPSESSID parameter in the URL is the Session ID. We can use $ _ GET to obtain the value, so that the Session ID can be transmitted between pages.

 
 
  1. // Save for one day
  2. $LifeTime=24* 3600;
  3. // Obtain the current Session name. The default value is PHPSESSID.
  4. $SessionName=Session_name();
  5. // Obtain the Session ID
  6. $SessionID= $ _ GET [$ sessionName];
  7. // Use session_id () to set the Session ID
  8. Session_id ($ sessionID );
  9.  
  10. Session_set_cookie_params ($ lifeTime );
  11. Session_start ();
  12. $ _ SESSION ["admin"] = true;
  13.  
  14. ?> 

For a VM, if all users' PHP Session sessions are saved in a temporary system folder, maintenance is difficult and security is reduced, you can manually set the Save path of the Session file. session_save_path () provides this function. We can direct the Session directory to a folder that cannot be accessed through the Web. Of course, this folder must have the read/write attribute.

 
 
  1. // Set a storage directory
  2. $SavePath="./Session_save_dir /";
  3. // Save for one day
  4. $LifeTime=24* 3600;
  5. Session_save_path ($ savePath );
  6. Session_set_cookie_params ($ lifeTime );
  7. Session_start ();
  8. $ _ SESSION ["admin"] = true;
  9.  
  10. ?> 

Like the session_set_cookie_params (); function, the session_save_path () function must also be called before the session_start () function is called.

We can also store arrays and objects in PHP Session sessions. There is no difference between an Operation Array and an operation variable. If you save an object, PHP will automatically serialize the object (also called serialization) and save it in the Session. The following example illustrates this:

 
 
  1. Person. php
  2.  
  3. Class person
  4. {
  5. Var $ age;
  6. Function output (){
  7. Echo $ this->Age;
  8. }
  9.  
  10. Function setAge ($ age ){
  11. $ This->Age= $ Age;
  12. }
  13. }
  14. ?> 
  15.  
  16. Setage. php
  17.  
  18.  
  19. Session_start ();
  20. Require_once "person. php ";
  21. $Person=NewPerson ();
  22. $ Person->SetAge (21 );
  23. $ _ SESSION ['person '] = $ person;
  24. Echo "check here to output age ";
  25.  
  26. ?> 
  27.  
  28. Output. php
  29.  
  30.  
  31. // Set the callback function to re-build the object.
  32. Ini_set ('unserialize _ callback_func ', 'mycallback ');
  33. Function mycallback ($ classname ){
  34. Include_once $ classname. ". php ";
  35. }
  36. Session_start ();
  37. $Person= $ _ SESSION ["person"];
  38. // Output 21
  39. $ Person->Output ();
  40.  
  41. ?> 

When we execute setage. in the php file, the setage () method is called, the age is set to 21, and the status is serialized and saved in the Session (PHP will automatically complete this conversion ), when it is switched to output. after php, to output this value, you must deserialize the saved object. Because an undefined class needs to be instantiated during deserialization, we have defined the callback function in the future, automatically contains person. php class file. Therefore, the object is restructured and the current age value is 21. Then, the output () method is called to output the value.

In addition, we can use the session_set_save_handler function to customize the PHP Session call method.


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.