Editor's note (2026): We've corrected the code in this 2014 tutorial. The original examples contained bugs (an undefined variable, curly "smart" quotes that PHP can't parse, and a missing backslash in newlines). The examples below work in current PHP versions.
Reading and writing files is one of PHP's most useful features. It's often used for logs, but you can use it for many other purposes. Here's the syntax, an example, and a short explanation for each step.
Opening a file
Use fopen() to open a file:
fopen(string $filename, string $mode)
$filename is the file's name (with its path if it's not in the same directory as your script). $mode sets what you can do with the file:
r— read only.r+— read and write.w— write only; empties the file first, or creates it if it doesn't exist.w+— read and write; empties the file first, or creates it.a— append; writes to the end of the file, creating it if needed.
Example: open conf.txt in read-only mode.
<?php
$handle = fopen('conf.txt', 'r');
Reading from a file
fread() reads from an open file:
fread(resource $handle, int $length)
Example: read the whole file and display it.
<?php
$filename = 'conf.txt';
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
fclose($handle);
echo htmlspecialchars($contents);
Close the file with fclose() when you're done to free resources; the contents stay in your variable.
Shortcut: to read a whole file at once, file_get_contents() is simpler:
<?php
$contents = file_get_contents('conf.txt');
Writing to a file
Use fwrite() to write a string to a file opened in a write mode:
<?php
$handle = fopen('config.txt', 'w');
fwrite($handle, '420');
fclose($handle);
To start a new line, use "\n" inside double quotes (single quotes don't interpret \n):
<?php
$handle = fopen('config.txt', 'w');
fwrite($handle, "420\n840\n1260");
fclose($handle);
This writes 420, 840, and 1260 on separate lines. Use mode a instead of w to add to the end of the file without erasing it.
Shortcut: file_put_contents('config.txt', "420\n840\n1260"); does the same in one line (add FILE_APPEND as a third argument to append).
Safety tips
- Check that
fopen()succeeded before using the handle (it returnsfalseon failure). - Never build file paths directly from user input; that can expose other files on your server.
- Store sensitive files outside your public web folder.
Need help with a PHP application or website? I.T. For Less can help — contact us.