search
HomeBackend DevelopmentPHP TutorialPHP7 Kernel Analysis 1 CGI and FastCGI

PHP7 Kernel Analysis 1 CGI and FastCGI

Apr 13, 2018 pm 02:46 PM
fastcgiphpphp7

The content of this article is about CGI and FastCGI of PHP7 Kernel Analysis 1. Now I share it with you. Friends in need can refer to it

CGI: It is the data between Web Server and Web Application An agreement for exchange.
FastCGI: Same as CGI, it is a communication protocol, but it has some optimizations in efficiency than CGI.
PHP-CGI: It is the interface program of PHP (Web Application) to the CGI protocol provided by Web Server.
PHP-FPM: It is the interface program of the FastCGI protocol provided by PHP (Web Application) to the Web Server. It also provides relatively intelligent task management

CGI workflow

1. If the client requests index.html, then the Web Server will find this file in the file system and send it to the browser. What is distributed here is static data.

2. When the Web Server receives the index.php request, it will start the corresponding CGI program, which is the PHP parser. Next, the PHP parser will parse the php.ini file, initialize the execution environment, then process the request, return the processed result in the format specified by CGI, exit the process, and the Web server will return the result to the browser.

FastCGI workflow

1. If the client requests index.html, then the Web Server will find this file in the file system and send it to the browser. What is distributed here is static data.

2. When the Web Server receives the index.php request, the FastCGI program (FastCGI initializes the execution environment when it starts, and each CGI process pool shares the execution environment) is in the CGI process pool. Select a CGI process to process the request, return the processed result in the format specified by CGI, and continue to wait for the next request.

Basic implementation of PHP-FPM

1. The implementation of PHP-FPM is to create a master process, create a worker pool in the master process and let it listen to the socket, and then Fork multiple sub-processes (work), and each of these sub-processes accepts the request. The processing of the sub-process is very simple. It blocks on accept after startup. When a request arrives, it starts to read the request data. After the reading is completed, it starts processing and then Return, no other requests will be received during this period, which means that the sub-process of PHP-FPM can only respond to one request at the same time. Only after this request is processed, the next request will be accepted

2. There is no direct communication between the PHP-FPM master process and the worker process. The master obtains the information of the worker process through shared memory, such as the current status of the worker process, the number of processed requests, etc. When the master process wants to kill a worker process, Notify the worker process by sending a signal.

3.PHP-FPM can monitor multiple ports at the same time. Each port corresponds to a worker pool, and each pool corresponds to multiple worker processes

PHP7 Kernel Analysis 1 CGI and FastCGI

Worker workflow

1. Waiting for the request: The worker process is blocked in fcgi_accept_request() waiting for the request;
2. Parsing the request: After the fastcgi request arrives, it is The worker receives, then starts to receive and parse the request data until the request data is completely arrived;
3. Request initialization: Execute php_request_startup(), this stage will call each extension: PHP_RINIT_FUNCTION();
4. Compile, Execution: The compilation and execution of the PHP script is completed by php_execute_script();
5. Shut down the request: After the request is completed, execute php_request_shutdown(). This stage will call each extension: PHP_RSHUTDOWN_FUNCTION(), and then enter step (1) to wait. Next request.

Master process management

1.static: This method is relatively simple. At startup, the master forks out the corresponding number of worker processes according to the pm.max_children configuration, that is, worker The number of processes is fixed

2.dynamic: Dynamic process management, first initialize a certain number of workers according to pm.start_servers when fpm starts. During operation, if the master finds that the number of idle workers is lower than the pm.min_spare_servers configuration number (indicating that there are too many requests and the worker cannot handle them), the worker process will be forked, but the total number of workers cannot exceed pm.max_children. If the master finds that the number of idle workers exceeds pm.max_spare_servers (indicating that there are too many idle workers) ) will kill some workers to avoid taking up too many resources. The master uses these 4 values ​​​​to control the number of workers

3.ondemand: This method is generally rarely used and does not allocate worker processes at startup. Wait until there is a request and then notify the master process to fork the worker process. The total number of workers does not exceed pm.max_children. The worker process will not exit immediately after the processing is completed. It will exit when the idle time exceeds pm.process_idle_timeout

PHP-FPM Event Manager

1.sp[1] Pipeline readable event: This event is used by master to process signals

2.fpm_pctl_perform_idle_server_maintenance_heartbeat(): This It is the main event in the implementation of process management. The master starts a timer, which is triggered every 1s. It is mainly used for worker management in dynamic and ondemand modes. The master will regularly check the number of worker processes in each worker pool and implement it through this timer. Control of the number of workers

3.fpm_pctl_heartbeat(): This event is used to limit the maximum time it takes for a worker to process a single request. There is a request_terminate_timeout configuration item in php-fpm.conf. If the total time it takes for a worker to process a request exceeds this value, then The master will send the kill -TERM signal to the worker process to kill the worker process. The unit of this configuration is seconds. The default value is 0, which means turning off this mechanism.

4.fpm_pctl_on_socket_accept(): The new value monitored by the master in ondemand mode The event of request arrival, because in ondemand mode fpm will not pre-create workers when it starts, and a child process will be generated only when there is a request, so the master process needs to be notified when the request arrives


The above is the detailed content of PHP7 Kernel Analysis 1 CGI and FastCGI. For more information, please follow other related articles on the PHP Chinese website!

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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software