Introduction to PHP File Creation and Manipulation
In today's web development landscape, PHP is one of the most widely used programming languages for server-side scripting. With PHP, you can create and
PHP runs on the server, so it can read and write real files on disk — generated reports, cached HTML, log entries, exported CSVs, uploaded user content, and configuration. This chapter covers the core workflow for creating and writing files: opening a file handle with the right mode, writing data, and closing the handle. It also explains when to reach for the simpler one-line helpers instead.
There are two families of file-writing tools in PHP:
- Stream handles —
fopen()/fwrite()/fclose(). Best when you write incrementally (appending log lines, streaming large output) and want fine control over the file mode. - One-shot helpers —
file_put_contents(). Best when you have the whole string in memory and just want to dump it to a file in one call.
We'll use the stream approach first because understanding modes is the key to everything else.
Creating and writing a file with fopen()
To write to a file you first open it with fopen(). It takes the file path and a mode string, and returns a file handle (a resource) that the other functions operate on:
<?php
$file = fopen("example.txt", "w"); // open for writing, truncating the file
fwrite($file, "This is an example.\n");
fclose($file); // always close the handleWhat each line does:
fopen("example.txt", "w")opensexample.txtin write mode. If the file does not exist it is created; if it does exist its contents are erased (truncated to zero length).fwrite()writes the string to the file and returns the number of bytes written (orfalseon failure).fclose()flushes any buffered data and releases the handle. Skipping it can leave data unwritten until the script ends.
A relative path like
"example.txt"is resolved against the script's current working directory. To be safe and predictable, prefer an absolute path, e.g.__DIR__ . "/example.txt".
File modes
The mode you pass to fopen() decides whether the file is created, truncated, or appended to, and whether you can read it. These are the modes that matter for creating and writing:
| Mode | Meaning | Creates file? | Existing content | Pointer starts at |
|---|---|---|---|---|
"w" | Write only | Yes | Erased | Beginning |
"w+" | Read + write | Yes | Erased | Beginning |
"a" | Append only | Yes | Kept | End |
"a+" | Read + append | Yes | Kept | End |
"x" | Write only, fail if file exists | Yes (only if new) | — | Beginning |
"x+" | Read + write, fail if exists | Yes (only if new) | — | Beginning |
Use "x" when you must not clobber an existing file — for example writing a lock file. Use "a" for logs, where each run should add to the file rather than wipe it.
Appending instead of overwriting
A very common mistake is using "w" for a log and wondering why the file only ever has one line. Open with "a" to keep the previous content and add to the end:
<?php
$log = fopen("app.log", "a"); // append mode — never erases
fwrite($log, "[" . date("Y-m-d H:i:s") . "] User logged in\n");
fclose($log);Run this twice and the file holds two timestamped lines instead of one.
The shortcut: file_put_contents()
When you already have the full content as a string, file_put_contents() does open, write, and close in a single call:
<?php
// Overwrite (or create) the file with this exact content:
file_put_contents("greeting.txt", "Hello, world!\n");
// Append instead of overwriting:
file_put_contents("app.log", "another line\n", FILE_APPEND);It returns the number of bytes written, or false on failure. This is the cleanest choice for small, in-memory payloads. Reach for fopen()/fwrite() when you write in a loop or need to keep the handle open across several operations.
Reading back what you wrote
To confirm a write, open the file in read mode ("r") and read it. The companion chapter PHP File Open/Read covers this in depth, but the stream version is:
<?php
$file = fopen("example.txt", "r");
$contents = fread($file, filesize("example.txt"));
fclose($file);
echo $contents;Here fread() reads up to filesize("example.txt") bytes — the whole file — into $contents. For a one-liner, file_get_contents() reads the entire file into a string with no handle to manage.
Handle errors and missing files
fopen() returns false (and emits a warning) if it cannot open the file — wrong permissions, a non-existent directory, or a read-only disk. Always check before you write:
<?php
$file = fopen("/no/such/dir/example.txt", "w");
if ($file === false) {
echo "Could not open the file for writing.";
} else {
fwrite($file, "ok");
fclose($file);
}Before reading a file you didn't create in the same run, confirm it exists with file_exists() to avoid warnings from filesize() or fread().
Other useful file functions
Beyond creating and writing, PHP ships a full toolkit for file management:
file_get_contents()— read an entire file into a string in one call.file_put_contents()— write a string to a file in one call.file_exists()— check whether a path exists before acting on it.unlink()— delete a file.rename()— rename or move a file.copy()— copy a file to a new path.
For uploaded files from a form, see PHP File Upload, and for the bigger picture of the filesystem API, see PHP File Handling.
Summary
- Open a file with
fopen($path, $mode); the mode controls create/truncate/append behaviour. - Use
"w"to overwrite,"a"to append, and"x"to refuse to clobber an existing file. fwrite()writes andfclose()flushes and releases the handle — always close.- For whole-string writes,
file_put_contents()is the concise one-call alternative. - Check
fopen()'s return value and usefile_exists()to write robust, warning-free code.