Beyond reading files, PHP allows you to create new files and write data to them. This is essential for logging, generating reports, or saving user configurations on the server.
The fopen() function is also used to create a file. If you use
"w" (write) or "a" (append) on a file that does not exist, PHP
will create it for you.
<?php
$myfile = fopen("testfile.txt", "w") or die("Unable to open file!");
?>
fwrite()The fwrite() function is used to write to a file. It takes two parameters:
the file handle and the string to be written.
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Selection of the correct mode is critical to avoid data loss.
| Mode | Behavior |
|---|---|
"w" |
Overwrites existing content. Pointer starts at the beginning. |
"a" |
Appends data. Pointer starts at the end of the file. Existing content is preserved. |
<?php
$myfile = fopen("log.txt", "a") or die("Unable to open file!");
$txt = "New login at " . date("H:i:s") . "\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
"w" mode will
erase all existing content in that file immediately. Always
double-check before using it!
\n or PHP_EOL to add new lines
to your text file, making it human-readable when opened in a text editor.
fopen() creates a file if it doesn't exist (in
w/a modes).fwrite() is the standard function for writing data."w" to start fresh and "a" to add to existing data.