In-depth interpretation of PHP operating mechanism_PHP tutorial
Let’s take a look at the following process of PHP operating mechanism through
:
1. We have never started it manually Through PHP related processes, it runs with the startup of Apache;
2. PHP is connected to Apache through the mod_php5.so module (specifically, SAPI, the server application programming interface);
3. PHP has three modules in total: kernel, Zend engine, and extension layer;
4. PHP kernel is used to handle requests, file streams, error handling and other related operations;
5. Zend Engine (ZE) is used to convert source files into machine language and then run it on a virtual machine;
6. The extension layer is a set of functions, class libraries and streams that PHP uses to perform some specific operations. For example, we need the mysql extension to connect to the MySQL database;
7. When ZE executes the program, it may need to connect to several extensions. At this time, ZE will hand over control to the extension and return it after processing the specific task;
8. Finally, ZE returns the program execution results to the PHP kernel, which then transmits the results to the SAPI layer and finally outputs them to the browser.
Deeply explore the operating mechanism of PHP
Wait, it’s not that simple. The above process is just a simplified version, let’s dig a little deeper to see what else is going on behind the scenes.
After Apache is started, the PHP interpreter is also started;
The PHP startup process has two steps;
The first step is to initialize some environment variables, which will be It works throughout the entire SAPI life cycle;
The second step is to generate some variable settings only for the current request.
The first step of PHP startup of PHP operating mechanism
I don’t know what the first and second steps are? Don’t worry, we’ll discuss this in detail next.
Let’s take a look at the first and most important step. The thing to remember is that the first step of the operation happens before any requests arrive. After starting Apache, the PHP interpreter also starts; PHP calls the MINIT method of each extension, thereby switching these extensions to an available state. Take a look at what extensions are opened in the php.ini file; MINIT means "module initialization". Each module defines a set of functions, class libraries, etc. to handle other requests.
A typical MINIT method is as follows:
PHP_MINIT_FUNCTION(extension_name){ /* Initialize functions, classes etc */ }
PHP startup mechanism of PHP operation mechanism Step Two
When a page request occurs, the SAPI layer hands over control to the PHP layer. So PHP sets the environment variables needed to reply to this request. At the same time, it also creates a variable table to store variable names and values generated during execution. PHP calls the RINIT method of each module, which is "request initialization". A classic example is the RINIT of the Session module. If the Session module is enabled in php.ini, the $_SESSION variable will be initialized and the relevant content will be read in when the RINIT of the module is called; the RINIT method can be regarded as a The preparation process starts automatically between program executions.
A typical RINIT method is as follows:
PHP_RINIT_FUNCTION(extension_name) { /* Initialize session variables, pre-populate variables, redefine global variables etc */ }
The first step of PHP shutdown in PHP operating mechanism
Just like PHP startup, PHP shutdown is also divided into two steps: Once the page is executed (whether it reaches the end of the file or is terminated with the exit or die function ), PHP will start the cleanup process. It will call the RSHUTDOWN method of each module in sequence. RSHUTDOWN is used to clear the symbol table generated when the program is running, that is, to call the unset function on each variable.
A typical RSHUTDOWN method is as follows:
PHP_RSHUTDOWN_FUNCTION(extension_name) { /* Do memory management, unset all variables used in the last PHP call etc */ }
The second step of PHP shutdown of PHP operating mechanism
Finally, all requests have been processed, SAPI is ready to be shut down, and PHP starts to execute the second step: PHP calls MSHUTDOWN of each extension method, this is the last chance for each module to release memory.
A typical RSHUTDOWN method is as follows:
PHP_MSHUTDOWN_FUNCTION(extension_name) { /* Free handlers and persistent memory etc */ }
In this way, 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.

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
