PHP异步---fsockopen

版权声明:科比龙篮 https://blog.csdn.net/qq_36514588/article/details/81868864

PHP 本身没有多线程的东西,但可以曲线的办法来造就出同样的效果,比如多进程的方式来达到异步调用,只限于命令模式

还有可用于 Web 程序中,那就是用fsockopen()、fputs() 来请求一个 URL 而无需等待返回.

使用fcockopen需要自己手动拼接出header部分

例如get方式

<?php
function asyn_demo() {
    $fp=fsockopen('localhost',80,$errno,$errstr,5);
    if(!$fp){
        echo "$errstr ($errno)<br />\n";
    }
    fputs($fp,"GET http://localhost/asy/asy_demo.php?name='qql' \r\n"); #请求的资源 URL 一定要写对
    fclose($fp);
} 
 
echo time().'<br>';
echo 'run asyn_sendmail<br>';
asyn_demo();
echo time().'<br>';  

post方式

<?php
$url = 'http://localhost/asy/asy_demo.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)? 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); 
} 
    

?>

异步需要执行的客户端

<?php
// 当执行过程中,客户端连接断开或连接超时,都会有可能造成执行不完整,因此需要加上
ignore_user_abort(true); // 忽略客户端断开 此处的代码需要php.ini开启相关的选项
set_time_limit(0);    // 设置执行不超时
$data = $_GET;
if(empty($data)){
	$data = $_POST;
}
$str = json_encode($data);
sleep(5);//模拟耗时任务
file_put_contents('./1.txt',$str);

猜你喜欢

转载自blog.csdn.net/qq_36514588/article/details/81868864
今日推荐