php异步调用
程序员文章站
2024-03-25 15:31:46
...
a.php
<?php
echo 'starttime:'.date('H:i:s', time()).'<br>';
$url = 'http://localhost/b.php';
$param = ['time'=>date('H:i:s', time())];
doAsyncRequest($url, $param);
echo 'endtime'.date('H:i:s', time());
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;
//fsockopen 打开一个网络连接或者一个Unix套接字连接
$fp = fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$fp) {
echo 'ERROR:'.$errno.' - '.$errstr.'<br>';
//端口改成800,下面会输出 ERROR:10061 - 由于目标计算机积极拒绝,无法连接。
} else {
$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);
}
}
b.php
<?php
sleep(2);//等待2秒
file_put_contents('file.txt', $_POST['time'].' - '.date('H:i:s', time())); exit;
访问结果 file.txt
08:17:05 - 08:17:07