To work with a file line by line, you open it, use it and close it. The three steps use fopen(), a read or write function, and fclose().
<?php
$handle = fopen("notes.txt", "w"); // open for writing
fwrite($handle, "Hello file\n");
fclose($handle); // always close
echo file_get_contents("notes.txt");
Hello file
fopen() returns a file handle (a resource, see Resources). You give that handle to the other file functions.
File modes
The second argument says what you want to do.
| Mode | Meaning | If the file does not exist |
|---|---|---|
r | Read only, start at the beginning | Error |
r+ | Read and write | Error |
w | Write only, empties the file first | Created |
w+ | Read and write, empties the file | Created |
a | Append: write at the end | Created |
a+ | Read and append | Created |
x | Create and write, fails if the file exists | Created |
c | Write without emptying | Created |
Add b (as in rb or wb) for binary files. It makes no difference on Linux, but on Windows it prevents line-ending conversion.
Check that opening worked
fopen() returns false and a warning when it fails: file missing, no permission or wrong path.
<?php
$handle = @fopen("does-not-exist.txt", "r");
if ($handle === false) {
echo "Could not open the file.";
} else {
fclose($handle);
}
Could not open the file.
The @ hides PHP’s warning here to keep the output short. In real code, avoid @, and handle the failure instead (for example log it and show a friendly message).
Why close the file
PHP closes open files when the script ends, but closing as soon as you are done:
- Frees the file for other processes.
- Makes sure buffered data is written.
- Keeps you from running out of open file handles in long scripts.
Safe pattern
<?php
$handle = fopen("log.txt", "a");
if ($handle === false) {
throw new RuntimeException("Cannot open log.txt");
}
try {
fwrite($handle, "Started\n");
} finally {
fclose($handle); // runs even if something above fails
}
echo "Done";
Done
finally guarantees fclose() runs. You will meet it in Error Handling.
When you do not need fopen
For small files, file_get_contents() and file_put_contents() are shorter. See file_get_contents() and file_put_contents(). Use fopen() when the file is large, or you need to read or write it in pieces.
Windows paths
C:/data/file.txt). PHP understands them on Windows, and you avoid escaping backslashes.