How to Write a File in PHP: Simple Guide with Examples
To write a file in PHP, use the
file_put_contents() function which writes data to a file in one step. Alternatively, use fopen() to open a file, fwrite() to write data, and fclose() to close the file.Syntax
file_put_contents() writes a string to a file in one step. It takes the filename and the data as arguments.
fopen() opens a file and returns a file handle. You specify the filename and mode (like 'w' for write).
fwrite() writes data to the opened file handle.
fclose() closes the file handle to save changes.
php
<?php // Using file_put_contents file_put_contents('filename.txt', 'Hello World'); // Using fopen, fwrite, fclose $file = fopen('filename.txt', 'w'); fwrite($file, 'Hello World'); fclose($file); ?>
Example
This example shows how to write the text "Hello, PHP!" into a file named example.txt using file_put_contents(). It creates the file if it does not exist or overwrites it if it does.
php
<?php $text = "Hello, PHP!"; file_put_contents('example.txt', $text); echo "File written successfully."; ?>
Output
File written successfully.
Common Pitfalls
- Not having write permission on the folder or file causes errors.
- Using
fopen()with wrong mode (like 'r' for reading only) will not allow writing. - For large files, using
file_put_contents()may be inefficient. - Not closing the file with
fclose()can cause data loss.
php
<?php // Wrong: fopen with read mode $file = fopen('file.txt', 'r'); fwrite($file, 'data'); // This will fail fclose($file); // Right: fopen with write mode $file = fopen('file.txt', 'w'); fwrite($file, 'data'); fclose($file); ?>
Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| file_put_contents | Write data to a file in one step | file_put_contents('file.txt', 'Hello'); |
| fopen | Open a file with a mode ('w' for write) | $file = fopen('file.txt', 'w'); |
| fwrite | Write data to an open file handle | fwrite($file, 'Hello'); |
| fclose | Close an open file handle | fclose($file); |
Key Takeaways
Use file_put_contents() for quick and simple file writing in PHP.
For more control, use fopen(), fwrite(), and fclose() together.
Always check file permissions to avoid write errors.
Close files after writing to ensure data is saved.
Use the correct mode ('w' for write) when opening files.