Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

flock

Description

Portable advisory file locking

Syntax

flock(
    resource $stream,
    int $operation,
    int &$would_block = null
): bool

Parameters

stream

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

operation

ConstantDescription
LOCK_SHacquire a shared lock (reader)
LOCK_EXacquire an exclusive lock (writer)
LOCK_UNrelease a lock (shared or exclusive)
LOCK_NBadd as a bitmask to one of the above operations if flock() should not block during locking

would_block

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

1 · stream operation · LOCK_SH

<?

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

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

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

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

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

        flock($stream, LOCK_UN);

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

fclose($stream);

?>
hello

2 · stream operation · LOCK_EX

<?

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

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

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

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

        fwrite($stream, $contents);

        flock($stream, LOCK_UN);

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

fclose($stream);

?>
hello

3 · stream operation · LOCK_NB

<?

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

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

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

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

        fwrite($stream, $contents);

        flock($stream, LOCK_UN);

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

fclose($stream);

?>
hello

4 · would_block

<?

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

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

    $operation = LOCK_EX;
    $would_block = 1;
    
    $return = flock($stream, $operation, $would_block);

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

        fwrite($stream, $contents);

        flock($stream, LOCK_UN);

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

fclose($stream);

?>
hello
HomeMenu