How to prevent PHP script running more than once?

前端 未结 6 917
臣服心动
臣服心动 2020-12-05 16:23

Currently, I tried to prevent an onlytask.php script from running more than once:

$fp = fopen(\"/tmp/\".\"onlyme.lock\", \"a+\");
if (flock($fp,         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 16:37

    Never use unlink for lock files or other functions like rename. It's break your LOCK_EX on Linux. For example, after unlink or rename lock file, any other script always get true from flock().

    Best way to detect previous valid end - write to lock file few bytes on the end lock, before LOCK_UN to handle. And after LOCK_EX read few bytes from lock files and ftruncate handle.

    Important note: All tested on PHP 5.4.17 on Linux and 5.4.22 on Windows 7.

    Example code:

    set semaphore:

    $handle = fopen($lockFile, 'c+');
    if (!is_resource($handle) || !flock($handle, LOCK_EX | LOCK_NB)) {
        if (is_resource($handle)) {
            fclose($handle);
        }
        $handle = false;
        echo SEMAPHORE_DENY;
        exit;
    } else {
        $data = fread($handle, 2);
        if ($data !== 'OK') {
            $timePreviousEnter = fileatime($lockFile);
            echo SEMAPHORE_ALLOW_AFTER_FAIL;
        } else {
            echo SEMAPHORE_ALLOW;
        }
        fseek($handle, 0);
        ftruncate($handle, 0);
    }
    

    leave semaphore (better call in shutdown handler):

    if (is_resource($handle)) {
        fwrite($handle, 'OK');
        flock($handle, LOCK_UN);
        fclose($handle);
        $handle = false;
    }
    

提交回复
热议问题