search

PHP life cycle analysis

May 15, 2018 pm 03:09 PM
phpcycle

This article mainly introduces the PHP life cycle. Before understanding the PHP life cycle, you need to understand how Apache is related to PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

1.Analysis of Apache operating mechanism


-----------------------------





#The overall diagram is as follows:




##Apache Hook mechanism Apache’s Hook mechanism refers to: Apache allows modules (including internal modules and external Modules,

such as mod_php5.so, mod_perl.so, etc.) inject custom functions into the request processing loop. In other words, the module can hook its own processing function in any processing stage of Apache, thereby participating in Apache's request processing process.

mod_php5.so/ php5apache2.dll is to inject the included custom functions into Apache through the Hook mechanism, and is responsible for processing php requests at each stage of the Apache processing process. .

#Now that we know how apache hooks to php, let’s take a look at the process logic after apache transfers to PHP.


##2.PHP running process Illustration

PHP start and end phases

After PHP starts executing It goes through two main phases: the beginning phase before processing the request and the ending phase after the request.


##2.1 SAPI runs PHP Several stages passed

Module initialization phase (Module init)

That is to call the method in PHP_MINIT_FUNCTION in each extension source code to initialize the module, apply for some variables required by the module, allocate memory, etc.

  1. Request initialization phase (Request init)

After receiving the client’s request Call the method in PHP_RINIT_FUNCTION of each extension to initialize the execution environment of the PHP script.

  1. Execute the PHP script (this step should be familiar to most PHP programmers, and the code you write is executed here)

  2. Request Shutdown

At this time, call the PHP_RSHUTDOWN_FUNCTION method of each extension to clean up the request site, and ZE begins to recycle variables and memory

  1. Close the module (Module shutdown)

When the Web server exits or the command line script is executed, the PHP_MSHUTDOWN_FUNCTION method in the extension source code will be called



##After the following steps: Start - Request starts - Request closes - End the SAPI interface implementation to complete its life cycle


##2.2 Starting phase

2.2.1 Module initialization Phase MINIT



# during the entire SAPI life cycle (for example, after Apache starts During the entire life cycle or the entire execution process of the command line program),
this process is only performed once.

After starting Apache, the PHP interpreter also starts;

PHP calls the MINIT method of each extension (module), thereby switching these extensions to an available state.

//This is also the reason why apache must be restarted when a new dll module is introduced. php.ini



#

PHP_MINIT_FUNCTION(myphpextension)
{
    // 注册常量或者类等初始化操作
    return SUCCESS; 
}





##2.2.2 Module activation phase RINIT


##

该过程发生在请求阶段, 例如通过url请求某个页面,则在每次请求之前都会进行模块激活(RINIT请求开始)。 

请求到达之后,SAPI层将控制权交给PHP层,PHP初始化本次请求执行脚本所需的环境变量

例如是Session模块的RINIT,如果在php.ini中启用了Session 模块,那在调用该模块的RINIT时就会初始化$_SESSION变量,并将相关内容读入; 然后PHP会调用所有模块RINIT函数,即“请求初始化”。 

在这个阶段各个模块也可以执行一些相关的操作, 模块的RINIT函数和MINIT函数类似 ,RINIT方法可以看作是一个准备过程,在程序执行之前就会自动启动。



PHP_RINIT_FUNCTION(extension_name) {
      /* Initialize session variables, pre-populate variables, redefine global variables etc */
}






2.3结束阶段

请求处理完后就进入了结束阶段, 一般脚本执行到末尾或者通过调用exit()或者die()函数,PHP都将进入结束阶段. 和开始阶段对应,结束阶段也分为两个环节,一个在请求结束后(RSHUWDOWN),一个在SAPI生命周期结束时(MSHUTDOWN).、


2.3.1请求结束后(RSHUWDOWN)



请求处理完后就进入了结束阶段,PHP就会启动清理程序。 

它会按顺序调用各个模块的RSHUTDOWN方法。 

RSHUTDOWN用以清除程序运行时产生的符号表,也就是对每个变量调用unset函数。




PHP_RSHUTDOWN_FUNCTION(extension_name) {
/* Do memory management, unset all variables used in the last PHP call etc */
}





2.3.2 SAPI生命周期结束时(MSHUTDOWN)


最后,所有的请求都已处理完毕 

SAPI也准备关闭了 

PHP调用每个扩展的MSHUTDOWN方法 

这时各个模块最后一次释放内存的机会。 

(这个是对于CGI和CLI等SAPI,没有“下一个请求”,所以SAPI立刻开始关闭。)



PHP_MSHUTDOWN_FUNCTION(extension_name) {
	/* Free handlers and persistent memory etc */
}



The entire PHP life cycle is over. It should be noted that "starting the first step" and "closing the second step" will only be executed when there is no request from the server.

Related recommendations:

##thinkPHP5.0 framework application request life cycle analysis

Vue component life cycle usage method


##React How long is the life cycle of Native components

#

The above is the detailed content of PHP life cycle analysis. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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