Home Menu

flock

Portable advisory file locking

Syntax

flock ( resource $handle , int $operation [, int &$wouldblock ] ) : bool

Parameters

handle

A file system pointer resource that is typically created using fopen().

operation

LOCK_SH acquire a shared lock (reader)
LOCK_EX acquire an exclusive lock (writer)
LOCK_UN release a lock (shared or exclusive)
LOCK_NB add as a bitmask to one of the above operations if you don't want flock() to block while locking
wouldblock

The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).

Return

Returns TRUE on success or FALSE on failure.

Examples

handle operation | LOCK_SH

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'r';

$handle = fopen($filename, $mode);

    $operation = LOCK_SH;
    
    $return = flock($handle, $operation);

    if ($return) {
        $length = filesize($filename);

        $contents = fread($handle, $length);

        flock($handle, LOCK_UN);

        echo $contents;
    } else {
        echo "could not lock";
    }

fclose($handle);

?>
Hello

handle operation | LOCK_EX

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'w';

$handle = fopen($filename, $mode);

    $operation = LOCK_EX;
    
    $return = flock($handle, $operation);

    if ($return) {
        $contents = "Hello";

        fwrite($handle, $contents);

        flock($handle, LOCK_UN);

        echo $contents;
    } else {
        echo "could not lock";
    }

fclose($handle);

?>
Hello

handle operation | LOCK_NB

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'w';

$handle = fopen($filename, $mode);

    $operation = LOCK_EX | LOCK_NB;
    
    $return = flock($handle, $operation);

    if ($return) {
        $contents = "Hello";

        fwrite($handle, $contents);

        flock($handle, LOCK_UN);

        echo $contents;
    } else {
        echo "could not lock";
    }

fclose($handle);

?>
Hello

wouldblock

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'w';

$handle = fopen($filename, $mode);

    $operation = LOCK_EX;
    $wouldblock = 1;
    
    $return = flock($handle, $operation, $wouldblock);

    if ($return) {
        $contents = "Hello";

        fwrite($handle, $contents);

        flock($handle, LOCK_UN);

        echo $contents;
    } else {
        echo "could not lock";
    }

fclose($handle);

?>
Hello

PHP

JesusBible
HTMLCSSJSPHPSVGMore
AboutTerms