以下是幾個使用範例。
第一個是基本範例。
<?php
$file = __DIR__ . '/text.txt';
if (is_file($file) && is_writable($file)) {
@unlink($file);
echo '<small style="color: #ccc;">' . $file . ' 已刪除。</small><br>' . PHP_EOL;
}
echo '<p>呼叫 <code>fastcgi_finish_request()</code>。</p>' . PHP_EOL;
echo '<p>如果成功,檔案 ' . $file . ' 將會被建立。</p>' . PHP_EOL;
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} else {
echo '<p style="color: red;">此伺服器不支援 <code>fastcgi_finish_request()</code> 函式。</p>' . PHP_EOL;
echo '現在結束。<br>' . PHP_EOL;
exit();
}
echo '這行不會被輸出。<br>' . PHP_EOL;
file_put_contents($file, date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
?>
如果成功,檔案 text.txt 將會被建立。
==========================
第二個是關於執行逾時的範例。
<?php
設定執行時間限制(5);
$file = __DIR__ . '/text.txt';
if (is_file($file) && is_writable($file)) {
@unlink($file);
echo '<small style="color: #ccc;">' . $file . ' 已刪除。</small><br>' . PHP_EOL;
}
echo '<p>測試逾時和 <code>fastcgi_finish_request()</code> 函式。</p>' . PHP_EOL;
echo '<p>設定逾時為 ' . ini_get('max_execution_time') . ' 秒。</p>' . PHP_EOL;
echo '<p>呼叫 <code>fastcgi_finish_request()</code>。</p>' . PHP_EOL;
echo '<p>如果成功,檔案 ' . $file . ' 將會被建立,但錯誤訊息會顯示在日誌中。</p>' . PHP_EOL;
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} else {
echo '<p style="color: red;">此伺服器不支援 <code>fastcgi_finish_request()</code> 函式。</p>' . PHP_EOL;
echo '現在退出。<br>' . PHP_EOL;
exit();
}
$i = 1;
while(true){
if ($i <= 10) {
file_put_contents($file, date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
$i++;
}
}
?>
我發現只要程式碼沒有超過 php.ini 或 set_time_limit() 函式設定的逾時時間,它就會持續運作。