Such a lock is not reliable. The fact is that if an error occurs in the script, or if the script is killed from the outside, the file will not be deleted and all subsequent launches will be unsuccessful. In order to avoid this, you must use flock () . The algorithm is about the following:
$lockFile = __FILE__.'.lock'; $hasFile = file_exists($lockFile); $lockFp = fopen($lockFile, 'w'); // Если блокировку получить не удалось, значит второй скрипт еще работает if (!flock($lockFp, LOCK_EX | LOCK_NB)) { die('Sorry, one more script is running.'); } // Если файл блокировки уже существовал, но не был залочен, // значит предыдущий запуск завершился некорректно if ($hasFile) { echo 'The previous running has been completed with an error.'; } // Все в порядке, блокировка lock получен // По окончании работы необходимо снять блокировку и удалить файл register_shutdown_function(function() use ($lockFp, $lockFile) { flock($lockFp, LOCK_UN); unlink($lockFile); }); // Дальше можем спокойно работать, не беспокоясь об повторном вызове // Даже если скрипт умрет, со смертью процесса блокировка автоматически снимется
As for the launch of long-running scripts, there are two complete ways here:
- Fork / run another script in a separate process and terminate the current one.
- When using PHP-FPM , call the fastcgi_finish_request () function. Then the request will complete correctly, and the script will continue to work as long as necessary.
The option, with the explicit sending of the Content-Length header, is not very good, because:
- Only suitable if php works via apache's mod_php. T.N. with nginx, this trick is no longer rolling.
- In some browsers, the connection will not be closed and, as a result, the page loading icon will spin until the script is finally completed (or until the user clicks the Stop button)
fopen($name, "w")
does not create a file. Use "w +" orfile_put_contents($name, '')
. - Sh4dow pm'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. >
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. >
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. >
'w +' Open for reading and writing; The file is zoomed. If the file doesn’t exist, attempt to create it - korwru