Simple PHP session (session) instructions
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
