您的位置:首页 > 编程语言 > PHP开发

PHP异步调用方法

2017-05-31 12:57 399 查看
客户端与服务器端是通过HTTP协议进行连接通讯,客户端发起请求,服务器端接收到请求后执行处理,并返回处理结果。

有时服务器需要执行很耗时的操作,这个操作的结果并不需要返回给客户端。但因为php是同步执行的,所以客户端需要等待服务处理完才可以进行下一步。

test-a.php
<?php
header("Content-type:text/html;charset=utf-8");

$url = 'http://localhost/test/testb.php';
echo 'starttime:'.microtime().'<br />';
$param = array(
'time'=>time()
);

doAsyncRequest($url, $param);
echo 'endtime'.microtime();

function doAsyncRequest($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);
}
?>
testb.php
<?php
header("Content-type:text/html;charset=utf-8");
sleep(15);//等待15秒
file_put_contents('filename.txt', $_POST);
print_r($_POST);
exit;
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: