主流程源代码,假设为async.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://' . $_SERVER["SERVER_NAME"]. '/async-2.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
curl_close($ch);
echo 'done';
异步执行程序文件,假设为:async-2.php
<?php
$i = 1;
while( $i <= 100 ){
z_log( date('Y-m-d H:i:s') . "\t" . $i );
sleep(1);
$i++;
}
function z_log($msg, $writeTime = true){
$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
if($writeTime){
fwrite($myfile, date('Y-m-d H:i:s')."\t");
}
fwrite($myfile, $msg."\r\n");
fclose($myfile);
说明:需要设置curl不直接输出,并且控制TIMEOUT为1,即前端至少需要等待1秒。经测试相对比较稳定,可以用。