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.

ModeBehavior when writing
wCreate or truncate: erases existing content
aCreate or append: keeps content, writes at the end
xCreate only: fails if the file already exists
cCreate or open without truncating, pointer at start

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);
}
?>
Note: Opening a file in 'w' mode immediately clears it, even if your script crashes before writing anything. When you only mean to add data, use 'a' so existing content is never lost.

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.