b.php
<?php $url = 'http://fsc.com/a.php'; $param = array( 'name'=>'fdipzone', 'gender'=>'male', 'age'=>30 ); doRequest($url, $param); echo "立马输出"; 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); stream_set_blocking($fp,true);//开启了手册上说的非阻塞模式 stream_set_timeout($fp,1);//设置超时 $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); /* //需要显示返回的信息,就用这个 fwrite($fp, $out); $content = ''; while (!feof($fp)) { $content .= fgets($fp); } fclose($fp); echo $content;//处理返回的信息 */ }
a.php
<?php // 当执行过程中,客户端连接断开或连接超时,都会有可能造成执行不完整,因此需要加上 ignore_user_abort(true); // 忽略客户端断开 此处的代码需要php.ini开启相关的选项 set_time_limit(0); // 设置执行不超时 $data = $_GET; if(empty($data)){ $data = $_POST; } $data['cont']= '延迟10秒写入,有上面的ignore函数在,网页客户端关闭网页,也可以照样执行'; $str = json_encode($data,JSON_UNESCAPED_UNICODE); sleep(10);//模拟耗时任务 file_put_contents('./1.txt',$str);
打开上面的b.php ,过10秒以后,a页面将接收到的东西写到1.txt里面,
打开b.php后,关闭页面也会执行异步写入操作,不会断开