Because PHP runs on the server, it can read and write files sitting on that same server — logs, cached data, simple text-based storage without needing a full database.
<?php
$content = file_get_contents("notes.txt");
echo $content;
?><?php
file_put_contents("notes.txt", "Hello, file!"); // overwrites
file_put_contents("notes.txt", "\nAnother line.", FILE_APPEND); // appends instead
?>For a large file, reading it all into memory at once with file_get_contents() is wasteful — opening it as a handle and reading one line at a time is more efficient:
<?php
$handle = fopen("notes.txt", "r");
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
?>Always close what you fopen()
Always call fclose() once you're done with a file handle opened via fopen() — leaving files open unnecessarily can lock them from other processes and leak resources on a long-running server.
<?php
if (file_exists("notes.txt")) {
echo "File exists.";
}
if (is_writable("notes.txt")) {
echo "File can be written to.";
}
?>Never trust a user-supplied file path
Any path used with these functions should never come directly from user input without careful validation — a visitor-controlled file path is a serious security risk (an attacker could potentially read or overwrite files well outside what you intended). This becomes especially relevant once file uploads are involved.