PHP Reading Files
In this page:
Reading with file_get_contents()
fopen($path, r) opens a file in read mode and returns a resource handle you pass to other file functions, or false if the file doesn't exist or can't be opened, which you should always check.
Example: Reading with file_get_contents()
<?php
file_put_contents("data.txt", "Sample content");
$handle = fopen("data.txt", "r");
if ($handle) {
echo "File opened for reading";
fclose($handle);
}
?>
Login to try C/C++/Java/PHP code in the editor
Reading Line-by-Line with fgets()
fread($handle, $length) reads up to a given number of bytes from an open file, while fgets($handle) reads just the next line, which is usually the more natural choice for line-oriented text files.
Example: Reading Line-by-Line with fgets()
<?php
file_put_contents("data.txt", "First line\nSecond line");
$handle = fopen("data.txt", "r");
echo fread($handle, 5) . "\n";
fclose($handle);
$handle = fopen("data.txt", "r");
echo fgets($handle);
fclose($handle);
?>
Login to try C/C++/Java/PHP code in the editor
Reading Character-by-Character with fgetc()
file_get_contents($path) reads an entire file into a single string in one call, which is simpler than manually opening, reading, and closing a handle when you just need the whole file's contents at once.
Example: Reading Character-by-Character with fgetc()
<?php
file_put_contents("data.txt", "Hello World");
echo file_get_contents("data.txt");
?>
Login to try C/C++/Java/PHP code in the editor
Reading Files as Arrays with file()
feof($handle) checks whether the read position has reached the end of the file, and is commonly used as the loop condition when reading a file line by line with fgets() inside a while loop.
Example: Reading Files as Arrays with file()
<?php
file_put_contents("data.txt", "Line 1\nLine 2\nLine 3");
$handle = fopen("data.txt", "r");
while (!feof($handle)) {
echo fgets($handle);
}
fclose($handle);
?>
Login to try C/C++/Java/PHP code in the editor
Reading Custom Bytes with fread()
Always close a file handle with fclose() once you're done, or rely on file_get_contents() which handles this automatically, since leaving handles open can exhaust the server's available file descriptors under load.
Example: Reading Custom Bytes with fread()
<?php
file_put_contents("data.txt", "Some content here");
$handle = fopen("data.txt", "r");
echo fread($handle, 4);
fclose($handle);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: