Home  >  Article  >  php教程  >  Simple PHP session (session) instructions

Simple PHP session (session) instructions

PHP中文网
PHP中文网Original
2016-08-22 10:14:312034browse

Nowadays, it is becoming more and more difficult for programmers. If you want to be proficient, you must trace the origin. This is actually the opposite of the increasingly advanced languages ​​​​and numerous frameworks that are currently flooding in, because they try to cover up the origin as much as possible to make it simple. , personally called it the programmer learning paradox.

Note: The author has been in contact with web development and PHP for about two weeks. The following content is suitable for beginners.

读 读 读 文 文 文 From the title of the article,

The idea of ​​the article first figure out what session is, what is the use of session, what is the routine used by Session, and how it is used in PHP.

2. Session (Session) Description

Before starting, I first recommend a basic theory book "HTTP Authoritative Guide", which is basic and essential knowledge for programmers. The author has an electronic version. If you need it, you can leave a message.

a. The origin of Session

Almost everyone is online, and billions of data are transmitted to each other on the network. The reason why data can be transmitted safely is based on the HTTP protocol, which is very familiar to you, right? In fact, what the HTTP protocol does is to provide a series of methods to complete your network access. When both parties establish an access, in principle, a session is established. Let’s take an example: Xiao Ming enters https://www.baidu.com/ in the browser (HTTPS is an encrypted version of HTTP, with an SSL encryption layer added). This is Xiao Ming’s request to Baidu, saying: "I want to see your interface", Baidu's servers received the message, which included what Xiao Ming wanted to do, and also included Xiao Ming's address (otherwise Baidu wouldn't know who to give the content to), and the server checked The information is OK, record Xiao Ming’s request, and send what Xiao Ming wants. A complete request is over. This is a conversation. The core of the conversation is Xiao Ming’s information filing (actually it also involves TCP/IP connection issues, which has nothing to do with this article, so ignore it) .

In fact, rather than building a Session, it is better to summarize a visit into a Session.

b. What can Session be used for? From the above content, we can get that each visit is a session, and the server must record the information. This has overhead. At the same time, it is unlikely that the same person will visit ten times in a row. Just build and save ten times or twenty times. One is to increase the overhead, and the other is also stupid. In other words, one person (the same computer and browser to be exact) can reuse a Session within a certain period of time. Why within a certain period of time? Because Session has a default expiration time,

the server will be cleared after expiration

(If not, think about how there are so many people in the world, it would be a waste to keep each one).

ok, since the same person, multiple visits are a Session (don’t doubt that the server cannot identify the same person, you can read the book recommended above for details), and the content of each visit is recorded, then it is also That is to say, the server knows all the behaviors within your session cycle. Then the next important role comes. The server can learn the behavioral preferences of this specific user by analyzing your access request. By doing Certain analysis can push some data that users like to care about. This is how advertising targeting comes about.

Of course there may be other users, performance, etc. I personally don’t particularly understand the mechanism, but that’s it here.

3. The use of Session in PHP

Through the above discussion, you can find that the concept of Session actually occurs on the server side.

PHP provides a series of configurations, functions, etc., to implement the Session function very well

. Session support in PHP is a method to save certain data during concurrent access. This allows you to build more customized programs and improve the attractiveness of your web site. A visitor to your web site will be assigned A unique id, the so-called session id. This id can be stored in a cookie on the user side or passed through the URL. Session support allows you to save the data in the request in the superglobal array

$_SESSION

. When When a visitor visits your site, PHP will automatically check (if session.auto_start is set to 1) or check at your request (explicitly via session_start() or implicitly via session_register()) whether the current session id is the one sent previously 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 independent user, the function of storing data separately for different users can be realized. Sessions are often used to save and share information between multiple page requests. Generally speaking, the Session ID is sent to the browser through a cookie, and the session data is also retrieved on the server side through the session ID. If the request does not contain session ID information, PHP will create a new Session and assign a new ID to the newly created Session.

The workflow of Session is very simple. When starting a Session, PHP will try to find the Session ID from the request (usually through the Session cookie). If the request does not contain Session ID information, PHP will create a new Session. After the Session starts, PHP will set the data in the Session to the $_SESSION variable. When PHP stops, it will automatically read the contents of $_SESSION, serialize it, and then send it to the session save manager for saving. By default, PHP uses the built-in file session saving manager (files) to complete session saving. You can also modify the Session save manager to be used through the configuration item session.save_handler (configuration item in php.ini). For the file session save manager, the session data is saved to the location specified by the configuration item session.save_path (configuration item in php.ini). A session can be started manually by calling the function session_start. If the configuration item session.auto_start is set to 1, then the Session will automatically start when the request starts. After the PHP script is executed, the session will automatically close. At the same time, you can also manually close the session by calling the function session_wirte_close().

b. The session information in php is configured in php.ini

This part is mentioned here because, without explaining the previous question, who knows what the configuration in php.ini is. The session.save_handler and session.save_path mentioned above are the configuration items in php.ini. I won’t go into detail here 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. The session will determine whether there is currently $_COOKIE[session_name()]; session_name() returns the COOKIE key value that saves the session_id. If it does not exist, it will be generated. A session_id, and then pass the generated session_id to the client as the COOKIE value. This is equivalent to performing the following COOKIE operation. On the contrary, if there is session_id =$_COOKIE[session_name]; then go to the folder specified by session.save_path to find the file named 'SESS_'.session_id(). Read the contents of the file, deserialize it, and then put it in $_SESSION middle.

When the session ends, the Session write operation will be performed or the session_write_close() operation will be performed manually.

There are generally three methods to destroy the Session in the code,   

     1. setcookie(session_name(),session_id(),time() -8000000,..); //Execute before logging out
     2. usset($_SESSION); //This will delete all $_SESSION data. After refreshing, COOKIE is passed, but there is no data.
            3. session_destroy(); //Delete $_SESSION Delete the session file and session_id

Appendix, quote a piece of code on the Internet, as the end.

    //SESSION初始化的时候调用    function open($save_path, $session_name)  
      {  global $sess_save_path;  $sess_save_path=$save_path;  return(true);  
      }  
  
      //关闭的时候调用    function close()  
      {  return(true);  
      }  
  
      function read($id)  
      {  global $sess_save_path;  $sess_file="$sess_save_path/sess_$id";  
      return (string) @file_get_contents($sess_file);  
      }  
      //脚本执行结束之前,执行写入操作    function write($id,$sess_data)  
      {  
  global$sess_save_path;  
  $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;  
      }

The above is the content of the simple PHP session (session) description. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn