这里有两个技巧也许有帮助。
I.在http连接关闭后继续执行。这意味着您可以在完成主要功能时立即关闭连接,然后继续进行日志处理。
<?php
ignore_user_abort(true);//avoid apache to kill the php running
ob_start();//start buffer output
echo "show something to user";//do something you need -- your main function
session_write_close();//close session file on server side if needed
header("Content-Encoding: none");//send header to avoid the browser side to take content as gzip format
header("Content-Length: ".ob_get_length());//send length header
header("Connection: close");//or redirect to some url
ob_end_flush();flush();//really send content, can't change the order:1.ob buffer to normal buffer, 2.normal buffer to output
//continue do something on server side
ob_start();
sleep(5);//the user won't wait for the 5 seconds
echo 'for log';//user can't see this
file_put_contents('/tmp/process.log', ob_get_contents());
// or call remote server like http://your.log.server/log.php?xxx=yyy&aaa=bbb
ob_end_clean();
?>
II。使用函数apache_note来写日志是比插入数据库更轻量的选择。因为Apache将在Apache运行期间打开日志文件并保留该句柄。它稳定而且非常快速。
Apache配置:
<VirtualHost *:80>
DocumentRoot /path/to/your/web
ServerName your.domain.com
ErrorLog /path/to/your/log/error_log
<Directory /path/to/your/web>
AllowOverride All
Order allow,deny
Allow from all
</Directory>
SetEnvIf Request_URI "/log\.php" mylog
LogFormat "%{mylog}n" log1
CustomLog "|/usr/sbin/cronolog /path/to/logs/mylog/%Y%m%d/mysite.%Y%m%d%H.log" log1 env=mylog
</VirtualHost>
PHP代码:
<?php
apache_note('mylog', session_id()); //you can log any data you need, see http://www.php.net/manual/en/function.apache-note.php
然后你可以使用我的技巧I和II,之后主网页连接关闭呼叫URL http://your.log.server/log.php?xxx=yyy&aaa=bbb记录您的详细资料。根本不需要额外的时间成本。
这是在这里解决: http://stackoverflow.com/questions/124462/asynchronous-php-calls – 2013-04-21 23:54:39