Heim  >  Artikel  >  Backend-Entwicklung  >  4种PHP异步执行的常用方式,_PHP教程

4种PHP异步执行的常用方式,_PHP教程

WBOY
WBOYOriginal
2016-07-12 09:02:47844Durchsuche

4种PHP异步执行的常用方式,

本文为大家讲述了php异步调用方法,分享给大家供大家参考,具体内容如下
客户端与服务器端是通过HTTP协议进行连接通讯,客户端发起请求,服务器端接收到请求后执行处理,并返回处理结果。
有时服务器需要执行很耗时的操作,这个操作的结果并不需要返回给客户端。但因为php是同步执行的,所以客户端需要等待服务处理完才可以进行下一步。
因此对于耗时的操作适合异步执行,服务器接收到请求后,处理完客户端需要的数据就返回,再异步在服务器执行耗时的操作。
1.使用Ajax 与 img 标记
原理,服务器返回的html中插入Ajax 代码或 img 标记,img的src为需要执行的程序。
优点:实现简单,服务端无需执行任何调用
缺点:在执行期间,浏览器会一直处于loading状态,因此这种方法并不算真正的异步调用。

$.get("doRequest.php", { name: "fdipzone"} );
<img  src="doRequest.php&#63;name=fdipzone" alt="4种PHP异步执行的常用方式,_PHP教程" >

2.使用popen
使用popen执行命令,语法:

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

优点:执行速度快
缺点:

  • 1).只能在本机执行
  • 2).不能传递大量参数
  • 3).访问量高时会创建很多进程

3.使用curl
设置curl的超时时间 CURLOPT_TIMEOUT 为1 (最小为1),因此客户端需要等待1秒

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

4.使用fsockopen
fsockopen是最好的,缺点是需要自己拼接header部分。

<&#63;php 
   
$url = 'http://www.example.com/doRequest.php'; 
$param = array( 
  'name'=>'fdipzone', 
  'gender'=>'male', 
  'age'=>30 
); 
   
doRequest($url, $param); 
   
function doRequest($url, $param=array()){ 
   
  $urlinfo = parse_url($url); 
   
  $host = $urlinfo['host']; 
  $path = $urlinfo['path']; 
  $query = isset($param)&#63; http_build_query($param) : ''; 
   
  $port = 80; 
  $errno = 0; 
  $errstr = ''; 
  $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); 
} 
   
&#63;>

注意:当执行过程中,客户端连接断开或连接超时,都会有可能造成执行不完整,因此需要加上

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

以上就是php异步调用方法的详细介绍,希望对大家的学习有所帮助。

您可能感兴趣的文章:

  • 深入PHP异步执行的详解
  • PHP 异步执行方法,模拟多线程的应用分析
  • PHP ajax 异步执行不等待执行结果的处理方法

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1084547.htmlTechArticle4种PHP异步执行的常用方式, 本文为大家讲述了 php异步调用方法 ,分享给大家供大家参考,具体内容如下 客户端与服务器端是通过HTTP协议...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn