PHP can read and write files on the server. That means you can create log files, read configuration data, process CSV uploads, or write error reports โ all from PHP. The file functions are straightforward and have been around forever.
Opening and Reading Files
The traditional way to read a file is with fopen(), fread(), and fclose(). fopen() takes a filename and a mode ("r" for read). fread() takes the file handle and the number of bytes to read. And fclose() closes the handle when you're done. fgets() reads one line at a time, which is useful for processing big files.
<?php
$handle = fopen("data.txt", "r");
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
?>
Try it Yourself โ
Shortcuts: file_get_contents and file_put_contents
If you just want to read an entire file into a string, file_get_contents() is your friend. It handles all the opening and closing internally. file_put_contents() does the opposite โ it writes a string to a file in one go. These are the functions you'll reach for 90% of the time.
<?php
$content = file_get_contents("data.txt");
echo $content;
file_put_contents("output.txt", "Hello from PHP!");
?>
Try it Yourself โ