This article mainly introduces the introduction of PHP asynchronous execution scripts. It has certain reference value. Now I share it with everyone. Friends in need can refer to it.
The asynchronous execution mentioned here is to let PHP scripts Suspend a script that performs specific operations in the background. After the main script exits, the suspended script can continue to execute. For example, to perform certain time-consuming operations or operations that can be performed in parallel, PHP can be executed asynchronously. The communication between the main script and the subscript can be through external files or memcached. The principle is to execute an external command through exec or system. Note: This article describes a Linux environment.
To make a script execute in the background under Linux, you can add an "&" symbol at the end of the command. Sometimes this is not enough, and you need to use the nohup command. For nohup, you can refer to http:// www.netingcn.com/linux-nohup.html.
The operations performed by the CLI environment and the Web environment are not the same. Let’s talk about the CLI environment first. You need to use nohup and & here, and also specify the output. If you don’t want to output the results, you can direct the output to /dev/null. Now let's do a test. Suppose there are main.php, sub1.php and sub2.php in a directory. The contents of sub1 and sub2 are the same and the sleep function is paused for a period of time. The code is as follows:
#main.php in the above file is used as the main script. Execute php main.php in the command line. You can see that the main.php script is executed quickly. Finish and exit. When using the ps aux | grep sub command to search for processes, you should be able to see the above two subscripts in the background, indicating that the subscripts have been successfully suspended.
In the Web environment, the execution of PHP scripts is handled by the cgi process started by the web server. As long as the script does not exit, it will always occupy the cgi process. When all the started cgi processes are occupied, it will Cannot process new requests. So for those scripts that may be time-consuming, you can use an asynchronous approach. The way to start a subscript is similar to the CLI. You must use & and specify the output (you have to direct it to /dev/null), but you cannot use nohup. For example:
When you access the script file in the browser, you can see that the response in the browser is completed. At the same time, use the ps command to view the background and you can see the sub1 and sub2 scripts.
Note that in the above example, if the php command is not in the PATH, you need to specify the complete path of the command. It is recommended to use the full path, especially under the Web.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
PHP’s file and directory operations
The above is the detailed content of Introduction to php asynchronous execution script. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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


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 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
