希望关闭浏览器后,程序能继续在后台跑,这种情况下需要用到ignore_user_abort()函数;
多的不说,直接上代码:
1 ignore_user_abort(true); //设置客户端断开连接时是否中断脚本的执行 2 set_time_limit(0); 3 $file = '/tmp/ignore_user.txt'; 4 if(!file_exists($file)) { 5 file_put_contents($file); 6 } 7 if(!$handle = fopen($file,'a+b')){ 8 echo "not open file :".$file; 9 exit; 10 } 11 $i=0; 12 while($i<100) { 13 $time = date("Y-m-d H:i:s",time()); 14 echo $time."\n"; 15 if(fwrite($handle,$time."\n")===false) { 16 echo "not write file:".$file; 17 exit; 18 } 19 echo "write file time:".$time."\n"; 20 $i++; 21 sleep(2); 22 } 23 24 fclose($handle);