How to use file_put_contents in PHP 8
Description
The file_put_contents
function writes data to a file.
file_put_contents in PHP 8
file_put_contents(
string $filename,
mixed $data,
int $flags = 0,
resource $context = ?
): int
Parameters
The file_put_contents
function returns the number of bytes written to the $filename
location. In case of failure, it returns false
. The $data
parameter holds the content to be written. The $flags
parameter modifies the operation according to the specifications mentioned below. The last parameter $context
specifies an optional stream context.
-
$filename:
This is the file destination at which the data should be written to. -
$data:
This is the data to be written. It can be a string, an array or a stream resource. If$data
is a stream resource, only the remaining buffer of the data will be copied. -
$flags
The flags can be any combination of the flags beneath in the table. You can combine them with the binary operator|
.Flag Description FILE_USE_INCLUDE_PATH If this flag is provided, the file destination will be looked up in the include directory ( include_path
).FILE_APPEND If the file at the destination location already exists, then the data will be appended to the end of the file. LOCK_EX With this flag, an exclusive lock on the file will be acquired. Behind the scenes a flock
function call happens. -
$context
If the$data
parameters is a stream resource, the$context
parameter modifies or enhances the behavior of the stream.
Example
$file = 'test.txt';
$data = "Hello World!";
// Write the contents to the file
file_put_contents($file, $data);
This is a fairly simple example which writes "Hello World!" to the file test.txt .