php file_put_contents function not working

php file_put_contents function not working

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Silent Failure of file_put_contents

When $f = file_put_contents("files/r.js", "Some text here") returns a falsy value, it is rarely because the function failed to write data in the way you expect. In PHP, file_put_contents returns an integer representing the number of bytes written. If that integer is zero, the function technically succeeded but wrote no content; if it returns false, the operation failed entirely.

The code snippet provided checks $f against a boolean truthiness. However, the logic often trips developers up not because of the file system write itself, but because the return value interpretation ignores the distinction between "zero bytes written" and "operation failed." In many scenarios, file_put_contents will return 0 when writing to an empty string or when the target path does not exist yet (depending on context), causing your if ($f) check to evaluate to false even if the file was created.

Before assuming a permission error or a filesystem outage, you must verify two specific conditions: whether the directory exists and is writable, and what the current permissions are on the target file or directory.

The Directory Existence Trap

The most common cause for file_put_contents returning false (or zero bytes) in this context is that the relative path "files/r.js" points to a directory that does not exist. PHP will not automatically create parent directories for you when writing a file unless you explicitly tell it to, and it certainly won't create the directory structure itself.

If the files folder is missing, the function throws an error or returns false depending on your error_reporting settings. If you are running in production with error reporting disabled, you might see no output at all, leading to the silent failure observed. To resolve this, ensure the parent directory exists before attempting to write:

if (!is_dir('files')) {
    mkdir('files', 0755, true);
}

The third argument to mkdir, true, makes the function recursive, allowing it to create intermediate directories if they are missing. However, be cautious here: creating a directory where one already exists as a file will throw a fatal error. Always validate that the path is not occupied by an existing file before attempting directory creation.

Permission Nuances and Ownership

Even if the directory exists, file_put_contents can fail due to permission restrictions. The function attempts to open the file with write permissions (typically 0644). If the parent directory lacks write permissions for the current user, or if the specific file is read-only, the operation fails.

Check your server's ownership and permissions using standard Linux commands:

ls -l files/
stat files/r.js

If the output shows that the directory is owned by root but your PHP script runs as a different user (common in shared hosting or containerized environments like Docker), you will encounter a permission denied error. In such cases, fixing ownership via chown or adjusting permissions with chmod is necessary. For instance, changing the directory to 0775 might be required if your PHP process runs under a group that has write access but not full read/write on the parent folder.

Handling Zero Bytes Correctly

There is a subtle edge case where file_put_contents returns 0. This happens when you try to overwrite a file with an empty string or when writing a string that evaluates to zero length in specific contexts (though less common with standard strings). More importantly, if the file already exists and has readonly attributes set at the OS level, the function might return 0 depending on how the underlying system handles the truncation attempt.

Your original check if ($f) treats 0 as false. If you intend to verify success based solely on whether bytes were written, this logic holds. However, if your goal is simply "did the write operation complete without error?", you need to distinguish between a zero-byte write and a failure. A safer approach involves checking for exceptions or relying on the return value strictly:

$bytesWritten = file_put_contents("files/r.js", "Some text here");

if ($bytesWritten === false) {
    // Actual failure occurred (e.g., permission denied, disk full)
} elseif ($bytesWritten === 0) {
    // Write succeeded but wrote zero bytes (file is empty or content was effectively null)
} else {
    // Success with $bytesWritten bytes
}

This distinction is vital for debugging. If you are seeing 0 in your logs and assuming failure, you might be misinterpreting a successful truncation of an existing file versus a genuine error state.

For production environments where robustness is key, consider using a library or framework that handles these edge cases explicitly. While Laravel provides excellent file utilities via the Storage facade that abstract away much of this complexity, understanding the raw file_put_contents behavior helps when debugging low-level issues directly within custom scripts.

Our network