← Back to PHP Course | Chapter 9: File Handling | Lesson 2 of 8

PHP Reading Files

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
<?php
file_put_contents("data.txt", "Sample content");
$handle = fopen("data.txt", "r");
if ($handle) {
    echo "File opened for reading";
    fclose($handle);
}
?>

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

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
<?php
file_put_contents("data.txt", "Hello World");
echo file_get_contents("data.txt");
?>

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

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
<?php
file_put_contents("data.txt", "Some content here");
$handle = fopen("data.txt", "r");
echo fread($handle, 4);
fclose($handle);
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.