PHP File Create and Write: A Beginner-Friendly Guide to Writing Files in PHP
Last updated 5 months, 2 weeks ago | 417 views 75 5
Introduction: Why Creating and Writing Files in PHP Matters
Creating and writing files is a fundamental task in PHP web development. Whether you're storing form data, logging user activity, generating reports, or saving configuration settings, file writing gives you a flexible way to store persistent data.
PHP offers multiple ways to create and write to files, ranging from low-level control using fopen() and fwrite() to simpler methods like file_put_contents().
In this tutorial, you'll learn the right way to create and write files in PHP, with code examples, best practices, and a working demo.
Methods to Create and Write Files in PHP
There are two main ways to write files in PHP:
-
Using
fopen()andfwrite()– more control and options -
Using
file_put_contents()– simpler and quicker method
✍️ 1. Creating and Writing Files with fopen() and fwrite()
Step-by-Step
Step 1: Use fopen() with Write Mode
$file = fopen("example.txt", "w"); // "w" = write mode (creates or truncates file)
-
"w" mode will create the file if it doesn't exist.
-
It will overwrite existing content if the file already exists.
Step 2: Write to the File with fwrite()
fwrite($file, "This is the first line.\n");
fwrite($file, "This is the second line.\n");
Step 3: Close the File
fclose($file);
Closing is crucial to release the file handle and avoid memory leaks.
⚡ 2. Simpler Way: Using file_put_contents()
file_put_contents("example.txt", "This is some text.\n");
✅ Pros:
-
Very concise
-
Automatically creates the file
-
Overwrites by default
Appending to a File
To append instead of overwrite:
file_put_contents("example.txt", "This line is added.\n", FILE_APPEND);
File Mode Options for fopen()
| Mode | Description |
|---|---|
| w | Write only; creates or truncates file |
| a | Append only; creates if not exists |
| x | Write only; creates new file; fails if exists |
| w+ | Read/Write; truncates |
| a+ | Read/Write; appends |
✅ Complete Working Example
<?php
$filename = "log.txt";
$data = "User logged in at " . date("Y-m-d H:i:s") . "\n";
// Option 1: Using fopen + fwrite
$file = fopen($filename, "a"); // Append mode
fwrite($file, $data);
fclose($file);
// Option 2: Using file_put_contents
file_put_contents($filename, $data, FILE_APPEND);
echo "Data successfully written to $filename";
?>
This script logs each access time into a file named log.txt.
Tips & Common Pitfalls
✅ Best Practices
-
Use
file_put_contents()for small, one-shot writes. -
Use
fopen()for large or frequent writes (e.g., in loops). -
Always check permissions (file must be writable).
-
Sanitize user input before writing to avoid file injection risks.
❌ Common Mistakes
-
Overwriting important files by using
"w"instead of"a". -
Forgetting to close file handles with
fclose(). -
Not checking if
fopen()orfwrite()returnfalseon failure. -
Using
file_put_contents()on large files (inefficient).
Comparison Table: fwrite() vs. file_put_contents()
| Feature | fwrite() + fopen() |
file_put_contents() |
|---|---|---|
| Code complexity | Medium | Low |
| Performance | Higher for big files | Ideal for small writes |
| Append support | Yes | Yes (with FILE_APPEND) |
| File creation | Yes | Yes |
| Manual close needed | Yes (fclose) |
No |
Conclusion: Writing Files in PHP – What You Should Remember
-
PHP provides simple yet powerful tools for writing to files.
-
Use
fopen()andfwrite()when you need control and efficiency. -
Use
file_put_contents()for quick and simple file writing. -
Always be cautious of overwriting data and ensure proper file permissions.
By mastering these functions, you unlock the ability to store logs, generate reports, export data, or even build file-based CMS features—all from scratch in PHP.