phasync
Blocking calls and the extension / file_put_contents

Function

file_put_contents

Writes a file, letting other coroutines run while it waits.

Description#

function file_put_contents(
    string $filename,
    mixed $data,
    int $flags = 0
): int|false

Inside a coroutine, it truncates the file (or appends, with FILE_APPEND) and writes $data with phasync::writable() between the writes. Outside one, it is the native file_put_contents(). Only FILE_APPEND and LOCK_EX of the native flags are handled.

Parameters#

$filename string
The file to write
$data mixed
A string, an array of strings that are joined, or a stream resource that is read to its end
$flags int = 0
FILE_APPEND and LOCK_EX

Return values#

The number of bytes written int|false

Errors / Exceptions#

ExceptionWhen
ExceptionWhen the file cannot be opened
RuntimeExceptionWhen a read of the stream resource or a write fails

Examples#

Example 1
use function phasync\file_put_contents;

file_put_contents('/tmp/log.txt', "started\n", FILE_APPEND);

See also#

  • file_get_contentsReads a whole file, letting other coroutines run while it waits.
  • flockLocks a file, letting other coroutines run while it waits for the lock.