PHP File Create Write
PHP creates a new file automatically the moment you open it for writing, and functions like fwrite() and file_put_contents() let you fill it with content.
Creating a file
There is no separate 'create file' command in PHP. Instead, opening a file with a writing mode creates it if it does not already exist. For example, fopen("log.txt", "w") will make log.txt when it is missing. The mode you choose controls whether existing content is kept or wiped, so picking the right one matters.
Creating a file and writing to it
<?php
$handle = fopen("log.txt", "w");
if ($handle) {
fwrite($handle, "Line one\n");
fwrite($handle, "Line two\n");
fclose($handle);
echo "File written successfully.";
}
?>Overwriting vs. appending
The difference between the 'w' and 'a' modes is important. Mode 'w' empties the file before writing, so it always starts fresh, which is fine for regenerating a file each time. Mode 'a' preserves what is already there and adds new data at the end, which is exactly what you want for log files that grow over time.
Appending a timestamped log entry
<?php
$entry = date("Y-m-d H:i:s") . " - user logged in\n";
$handle = fopen("access.log", "a");
if ($handle) {
fwrite($handle, $entry);
fclose($handle);
}
?>The one-line alternative
For simple cases, file_put_contents() writes a string to a file in a single call, opening, writing, and closing for you. Pass the FILE_APPEND flag to add to the file instead of replacing it. This is the most convenient way to write small amounts of data.
Writing with file_put_contents()
<?php
// Replace the file's contents
file_put_contents("data.txt", "fresh content\n");
// Append without erasing what is there
file_put_contents("data.txt", "added line\n", FILE_APPEND);
?>- fopen() with 'w', 'a', 'x', or 'c' creates the file if it does not exist.
- fwrite() returns the number of bytes written, or false on failure.
- The web server's user must have write permission on the target directory.
- file_put_contents() is the quickest option for writing a whole string in one step.