Php session basic knowledge

Source: Internet
Author: User
In php, session is a global variable on the server that can be transferred between pages. Therefore, session is often used for logon verification by server-side User members. session security is also very high,

In php, session is a global variable on the server that can be transferred between pages. Therefore, session is often used for logon verification by server-side User members. session security is also very high, next I will introduce the basic php session knowledge.

What do you think about Sessions? I don't know whether you have studied it. Today, Dana's php Training teacher wants to share some content in this area with you. I hope you will like it.

How long is the session lifecycle?

1. when the browser ends, its lifecycle also ends, but the file still exists in/tmp/(sess _???)

2. the sessionID will be re-allocated when you re-open the browser next time. if you use session_id () to bring back the previous ID, The sess _???, Retrieve all the previously set parameters

3. you can modify the remaining time of the session file in PHP. ini.

Session. gc_maxlifetime = 1440; after this number of seconds, stored

Data will be seen as 'garbage' and

Cleaned up by the gc process

The default value is 1440 seconds, 24 minutes

Storage path issues that need to be paid attention to when using session,Check the session settings in php. ini.

  1. [Session]
  2. Session. save_handler = files; handler used to store/retrieve data
  3. Session. save_path =/tmp; argument passed to save_handler
  4. In the case of files, this is
  5. Path where data files are stored

By default, it is stored in the/tmp directory, which may not be true. you 'd better change it to your php installation path, such as c:/php.

A thorough understanding of the php session mechanism

1. session. save_handler = files

* 1. session_start ()

1. session_start () is the beginning of the session mechanism. it has a certain probability to enable garbage collection because the session is stored in the file,

The garbage collection of PHP itself is invalid, and the collection of sessions is to delete files. this probability is determined based on the configuration of php. ini,

However, some systems use session. gc_probability = 0, which means the probability is 0, but garbage collection is implemented through the cron script.

  1. Session. gc_probability = 1
  2. Session. gc_divisor = 1000
  3. Session. gc_maxlifetime = 1440 // The default expiration time is 24 minutes.
  4. // The probability is session. gc_probability/session. gc_divisor. result 1/1000,
  5. // It is not recommended to set too small because session garbage collection requires checking whether each file has expired.
  6. Session. save_path = // It seems that different systems have different default values. one of the following settings is "N;/path"
  7. // This is a random hierarchical storage. in this case, garbage collection does not work and you need to write your own scripts.

2. the session checks whether $ _ COOKIE [session_name ()]; session_name () returns the COOKIE key value for saving session_id. this value can be found in php. ini.

Session. name = PHPSESSID // Default value: PHPSESSID

3. if it does not exist, a session_id is generated, and the generated session_id is passed to the client as the COOKIE value. the following COOKIE operation is performed. Note that the setcookie () operation is performed in this step. the COOKIE is sent in the header, which cannot be output before, PHP has another function session_regenerate_id (). If this function is used, no output is available.

  1. Setcookie (session_name (),
  2. Session_id (),
  3. Session. cookie_lifetime, // The default value is 0.
  4. Session. cookie_path, // The default '/' is valid in both the current program and directory.
  5. Session. cookie_domain, // null by default
  6. )

4. if session_id =$ _ COOKIE [session_name];

Go to the folder specified by session. save_path to find the file named 'sess _ '. session_id.

Read the file content deserialization and put it in $ _ SESSION.

* 2. assign a value to $ _ SESSION

For example, if a new value $ _ SESSION ['test'] = 'Blah' is added, this $ _ SESSION will only be maintained in the memory. when the script execution ends, write the $ _ SESSION value to the folder specified by session_id, and then close related resources. in this phase, you may change the session_id, for example, destroy an old session_id and generate a new session_id. half is used for custom session operations and role conversion, such as Drupal. anonymous users of Drupal have a SESSION. after logon, they need to replace the new session_id.

  1. If (isset ($ _ COOKIE [session_name ()]) {
  2. Setcookie (session_name (), '', time ()-42000, '/'); // The old session cookie expires.
  3. }
  4. Session_regenerate_id (); // This step generates a new session_id
  5. // Session_id () returns a new value.

* 3. write SESSION

At the end of the script, the SESSION write operation will be executed to write the $ _ SESSION value to the session_id named file, which may already exist and may need to be created.

* 4. destroy the SESSION

The COOKIE sent by the SESSION is generally an instant COOKIE, which is stored in the memory and will expire only when the browser is closed. if the user needs to forcibly expire, such as logging out, rather than closing the browser, the SESSION needs to be destroyed in the code. There are many methods:

O 1. setcookie (session_name (), session_id (), time ()-8000000,...); // run the command before logging out.

O 2. usset ($ _ SESSION); // This will delete all $ _ SESSION data. after refreshing, a COOKIE is sent, but no data exists.

O 3. session_destroy (); // This function is more thorough. delete $ _ SESSION to delete the session file and session_id.

When the browser is not closed, refresh the page again. cookies are sent from both 2 and 3, but no data is found.

2. session. save_handler = user

The custom session processing mechanism is more intuitive.

* Session_set_save_handler ('open', 'close', 'read', 'write', 'deststroy', 'gc ');

1. session_start (), execute open ($ save_path, $ session_name) to open the session operation handle

$ Save_path is session. save_path when session. save_handler = files,

However, if you do not use these two parameters, return TRUE directly and execute read ($ id) to read data from them. // This parameter is automatically passed as session_id (). you can use this parameter to perform operations.

* 2. script execution ends

Execute write ($ id, $ sess_data) // Two parameters, which are very simple.

* 3. if the user needs session_destroy ()

Run destroy first.

The code is as follows:

  1. // Called during SESSION initialization
  2. Function open ($ save_path, $ session_name)
  3. {
  4. Global $ sess_save_path;
  5. $ Sess_save_path = $ save_path;
  6. Return (true );
  7. }
  8. // Called when disabled
  9. Function close ()
  10. {
  11. Return (true );
  12. }
  13. Function read ($ id)
  14. {
  15. Global $ sess_save_path;
  16. $ Sess_file = "$ sess_save_path/sess _ $ id ";
  17. Return (string) @ file_get_contents ($ sess_file );
  18. }
  19. // Execute the write operation before the script execution ends.
  20. Function write ($ id, $ sess_data)
  21. {
  22. Echo "sdfsf ";
  23. Global $ sess_save_path;
  24. $ Sess_file = "$ sess_save_path/sess _ $ id ";
  25. If ($ fp = @ fopen ($ sess_file, "w ")){
  26. $ Return = fwrite ($ fp, $ sess_data );
  27. Fclose ($ fp );
  28. Return $ return;
  29. } Else {
  30. Return (false );
  31. }
  32. }
  33. Function destroy ($ id)
  34. {
  35. Global $ sess_save_path;
  36. $ Sess_file = "$ sess_save_path/sess _ $ id ";
  37. Return (@ unlink ($ sess_file ));
  38. }
  39. Function gc ($ maxlifetime)
  40. {
  41. Global $ sess_save_path;
  42. Foreach (glob ("$ sess_save_path/sess _ *") as $ filename ){
  43. If (filemtime ($ filename) + $ maxlifetime <time ()){
  44. @ Unlink ($ filename );
  45. }
  46. }
  47. Return true;
  48. }

Example:Before you store user information in a PHP Session, you must start the session.

Note:The session_start () function must be located inThe code is as follows:

  1. Php session_start ();?>
  2.  
  3.  
  4.  
  5.  

The above code registers a user's session with the server so that you can start to save the user information and assign a UID to the user session.

Store Session variables

The correct method for storing and retrieving session variables is to use the PHP $ _ SESSION variable. the code is as follows:

  1. Session_start ();
  2. // Store session data
  3. $ _ SESSION ['View'] = 1;
  4. ?>
  5.  
  6.  
  7. // Retrieve session data
  8. Echo "Pageviews =". $ _ SESSION ['View'];
  9. ?>
  10.  
  11.  
  12. // Output:
  13. // Pageviews = 1

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.