Labs ICT
โญ Pro Login

File Handling

1 min read | PHP Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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);
?>

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!");
?>

๐Ÿงช Quick Quiz

Which function reads the entire contents of a file into a string?