Php的异步处理
Php本身是单线程的,在处理一些耗时长的语句,如发邮件、发短信等,会造成用户长时间的等待,用户体验极差,这时候我们就需要“异步处理”来解决,异步处理的方法有很多,最常用的是借助前台Ajax技术实现,除了这种方法外我们还可以用下面两种方式实现。
方法一:用fsockopen函数
Index.php
<?php function thread(){ $fp = fsockopen("localhost", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET / thread.php / HTTP/1.1\r\n"; $out .= "Connection: close\r\n\r\n";//连接成功即关闭,不适用长连接 fputs($fp, $out); fclose($fp); } } echo time().'<br>'; echo 'open thread……<br>'; thread(); echo time().'<br>'; ?>
thread.php
1 <?php 2 3 sleep(5); 4 5 $dir="c:/".time().".txt"; 6 7 fopen($dir,'w'); 8 9 ?>
执行主文件index.php后,会调用thread.php后台执行,thread.php可以执行执行复杂耗时较长的语句,如发送邮件,发送短信等。
方法二:用curl函数
有时候服务器出于安全考虑会禁用fsockopen函数,我们还可以用下面方法实现
Index.php
1 <?php 2 3 $ch = curl_init(); 4 5 curl_setopt($ch,CURLOPT_URL,"http://localhost/thread.php"); 6 7 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 8 9 curl_setopt($ch,CURLOPT_TIMEOUT,1); 10 11 curl_exec($ch); 12 13 curl_close($ch); 14 15 ?>
thread.php
1 <?php 2 3 sleep(5); 4 5 $dir="c:/".time().".txt"; 6 7 fopen($dir,'w'); 8 9 ?>
参考文章:http://www.cnblogs.com/gaoxu387/archive/2011/10/26/2224740.html