时间:2021-07-01 10:21:17 帮助过:14人阅读
1、使用前端Ajax处理
$.get("doAsync.php", { name: 'raykaeso',job:'PHP Programmer'} );
2、使用popen,执行本地文件
pclose(popen('php /var/www/doAsync.php &', 'r'));
3、使用curl
设置curl的超时时间 CURLOPT_TIMEOUT 为1 (最小为1),因此客户端需要等待1秒,curl请求地址必须为绝对路径
$param = array( 'name'=>'raykaeso', 'job'=>'PHP Programmer' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://www.example.com/doAsync.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param)); //将数组转换为URL请求字符串 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_exec($ch); curl_close($ch);
4、使用fsockopen,需要自己拼接header部分
function doRequest($url, $param=array(),$timeout =10){ $urlParmas = parse_url($url); $host = $urlParmas['host']; $path = $urlParmas['path']; $port = isset($urlParmas['port'])? $urlParmas['port'] :80; $errno = 0; $errstr = ''; $fp = fsockopen($host, $port, $errno, $errstr, $timeout); $query = isset($param)? http_build_query($param) : ''; $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); } $url = 'http://www.example.com/doAsync.php'; $param = array( 'name'=>'raykaeso', 'job'=>'PHP Programmer' ); doRequest($url, $param);
注意:
1、如果使用Apache作为Web服务器,让PHP支持异步首先必须得在Apache配置文件httpd.conf配置enablesendfile on。
2、在异步执行的PHP文件中建议加上一下两个配置:
ignore_user_abort(true); // 忽略客户端断开 set_time_limit(0); // 设置执行不超时