Backend Development 3 min read

PHP file_put_contents Function: Usage, Parameters, and Examples

This article explains PHP's file_put_contents function, detailing its purpose of writing strings, arrays, or streams to files, describing each parameter (filename, data, flags, context), return values, and providing two practical code examples demonstrating basic usage and appending with FILE_APPEND and LOCK_EX flags.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP file_put_contents Function: Usage, Parameters, and Examples

The file_put_contents() function in PHP writes a string, array, or stream to a file, providing a convenient alternative to using fopen() , fwrite() , and fclose() sequentially.

Parameters :

filename : the path of the file to write to.

data : the data to write; can be a string, an array (which will be joined), or a stream resource.

flags : optional integer flags combined with the bitwise OR operator (e.g., FILE_APPEND , LOCK_EX ).

context : a stream context resource.

Return value : the number of bytes written on success, or FALSE on failure.

Example 1 – Basic write :

<?php
$file = 'people.txt';
$current = file_get_contents($file);
$current .= "John Smith\n";
file_put_contents($file, $current);
?>

Example 2 – Append with flags :

<?php
$file = 'people.txt';
$person = "John Smith\n";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
BackendPHPfile handlingphp-functionsfile_put_contents
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.