search
HomeBackend DevelopmentPHP TutorialFour common ways of asynchronous execution in PHP

This article describes the PHP asynchronous calling method and shares it with you for your reference. The specific content is as follows

The client and the server communicate through the HTTP protocol. The client initiates a request and the server receives it. After receiving the request, the processing is performed and the processing result is returned.

Sometimes the server needs to perform a time-consuming operation, and the result of this operation does not need to be returned to the client. But because PHP is executed synchronously, the client needs to wait for the service to be processed before proceeding to the next step.

Therefore, time-consuming operations are suitable for asynchronous execution. After the server receives the request, it returns after processing the data required by the client, and then performs time-consuming operations asynchronously on the server.

1. Use Ajax and img tag

Principle: Insert Ajax code or img tag into the HTML returned by the server. The src of img is the program that needs to be executed.

Advantages: Simple implementation, the server does not need to perform any calls

Disadvantages: During execution, the browser will always be in the loading state, so this method is not a true asynchronous call.

$.get("doRequest.php", { name: "fdipzone"} );
<img  src="/static/imghwm/default1.png"  data-src="doRequest.php?name=fdipzone"  class="lazy"   alt="Four common ways of asynchronous execution in PHP" >

2. Use popen

Use popen to execute commands, syntax:

// popen — 打开进程文件指针 
resource popen ( string $command
, string $mode
)
pclose(popen(&#39;php /home/fdipzone/doRequest.php &&#39;, &#39;r&#39;));

Advantages: Fast execution

Disadvantages:

1). Can only be executed on this machine

2). Cannot pass a large number of parameters

3). Many processes will be created when the traffic is high

3. Use curl

Set curl's timeout CURLOPT_TIMEOUT to 1 (minimum is 1), so the client needs to wait for 1 second

<?php
$ch
= curl_init();
$curl_opt
= array(
  CURLOPT_URL, &#39;http://www.example.com/doRequest.php&#39;
  CURLOPT_RETURNTRANSFER,1,
  CURLOPT_TIMEOUT,1
);
curl_setopt_array($ch, $curl_opt);
curl_exec($ch);
curl_close($ch);
?>

4. Using fsockopen

fsockopen is the best. The disadvantage is that you need to splice the header part yourself.

<?php
    
$url
= &#39;http://www.example.com/doRequest.php&#39;;
$param
= array(
  &#39;name&#39;=>&#39;fdipzone&#39;,
  &#39;gender&#39;=>&#39;male&#39;,
  &#39;age&#39;=>30
);
    
doRequest($url, $param);
    
function
doRequest($url, $param=array()){
    
  $urlinfo
= parse_url($url);
    
  $host
= $urlinfo[&#39;host&#39;];
  $path
= $urlinfo[&#39;path&#39;];
  $query
= isset($param)? http_build_query($param) : &#39;&#39;;
    
  $port
= 80;
  $errno
= 0;
  $errstr
= &#39;&#39;;
  $timeout
= 10;
    
  $fp
= fsockopen($host, $port, $errno, $errstr, $timeout);
    
  $out
= "POST ".$path." HTTP/1.1\r\n";
  $out
.= "host:".$host."\r\n";
  $out
.= "content-length:".strlen($query)."\r\n";
  $out
.= "content-type:application/x-www-form-urlencoded\r\n";
  $out
.= "connection:close\r\n\r\n";
  $out
.= $query;
    
  fputs($fp, $out);
  fclose($fp);
}
    
?>

Note: During the execution process, the client connection is disconnected or the connection times out, which may cause incomplete execution, so you need to add

ignore_user_abort(true); // 忽略客户端断开
set_time_limit(0);    // 设置执行不超时

For more PHP related knowledge, please visit PHP tutorial!

The above is the detailed content of Four common ways of asynchronous execution in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

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

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

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.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

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

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

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

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 Article

Hot Tools

mPDF

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),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools