How to Use file_put_contents in PHP: Syntax and Examples
Use
file_put_contents in PHP to write a string or data to a file quickly. It takes the filename and the data as main arguments and returns the number of bytes written or false on failure.Syntax
The file_put_contents function writes data to a file. It has three main parts:
- filename: The path to the file you want to write to.
- data: The string or data you want to save in the file.
- flags (optional): Controls how data is written, like appending instead of overwriting.
The function returns the number of bytes written or false if it fails.
php
int file_put_contents(string $filename, mixed $data, int $flags = 0, resource $context = null)
Example
This example shows how to write a simple string to a file named example.txt. It overwrites the file if it exists or creates it if it doesn't.
php
<?php $file = 'example.txt'; $content = "Hello, this is a test message!\n"; $result = file_put_contents($file, $content); if ($result !== false) { echo "Successfully wrote $result bytes to $file."; } else { echo "Failed to write to $file."; } ?>
Output
Successfully wrote 29 bytes to example.txt.
Common Pitfalls
Common mistakes when using file_put_contents include:
- Not having write permission for the file or directory, causing failure.
- Forgetting that by default it overwrites the file instead of appending.
- Passing non-string data without converting it, which can cause unexpected results.
Use the FILE_APPEND flag to add data to the end of the file instead of replacing it.
php
<?php // Wrong: overwrites file unintentionally file_put_contents('log.txt', "First line\n"); file_put_contents('log.txt', "Second line\n"); // Right: appends to the file file_put_contents('log.txt', "First line\n"); file_put_contents('log.txt', "Second line\n", FILE_APPEND); ?>
Quick Reference
| Parameter | Description |
|---|---|
| filename | Path to the file to write. |
| data | Data to write (string or binary). |
| flags | Optional flags like FILE_APPEND to append data. |
| context | Optional stream context resource. |
Key Takeaways
file_put_contents writes data to a file and returns bytes written or false on failure.
By default, it overwrites the file; use FILE_APPEND flag to add data instead.
Ensure the script has write permissions to the target file or directory.
Always check the return value to confirm the write succeeded.
You can write strings or binary data using this function.