Table of Contents
2. Session (Session) Description
a. The origin of Session
the server will be cleared after expiration

a. Basic usage of session in php

b. The session information in php is configured in php.ini
c. The session mechanism in php
Home php教程 php手册 Simple PHP session (session) instructions

Simple PHP session (session) instructions

Aug 22, 2016 am 10:14 AM

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;  
      }
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles