這裏有兩個技巧也許有幫助。
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