0
0
PHPprogramming~5 mins

Reading files (fread, fgets, file) in PHP

Choose your learning style9 modes available
Introduction

Reading files lets your program get information stored in text files. This helps you use data saved earlier or from other sources.

You want to read a list of names saved in a text file.
You need to process a log file line by line to find errors.
You want to load configuration settings stored in a file.
You want to read the entire content of a file into a variable quickly.
You want to read a file line by line to save memory.
Syntax
PHP
<?php
// Open a file for reading
$handle = fopen('filename.txt', 'r');

// Read fixed number of bytes
$content = fread($handle, 100);

// Read one line
$line = fgets($handle);

// Close the file
fclose($handle);

// Read entire file into array of lines
$lines = file('filename.txt');
?>

fopen opens the file and returns a handle to use for reading.

fread reads a set number of bytes from the file.

fgets reads one line at a time.

file reads the whole file into an array, each element is a line.

Examples
Reads first 50 bytes from 'data.txt' and prints it.
PHP
<?php
$handle = fopen('data.txt', 'r');
$content = fread($handle, 50);
fclose($handle);
echo $content;
?>
Reads 'data.txt' line by line and prints each line.
PHP
<?php
$handle = fopen('data.txt', 'r');
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);
?>
Reads entire file into an array, then prints each line.
PHP
<?php
$lines = file('data.txt');
foreach ($lines as $line) {
    echo $line;
}
?>
Sample Program

This program creates a small file, then reads it three ways: first 10 bytes with fread, line by line with fgets, and all lines at once with file. It prints the results so you can see how each method works.

PHP
<?php
// Sample program to read a file using fread, fgets, and file

// Create a sample file
file_put_contents('sample.txt', "Hello\nWorld\nPHP File Reading!\n");

// Using fread
$handle = fopen('sample.txt', 'r');
$content = fread($handle, 10); // read first 10 bytes
fclose($handle);
echo "Using fread (10 bytes):\n" . $content . "\n\n";

// Using fgets
$handle = fopen('sample.txt', 'r');
$line1 = fgets($handle); // read first line
$line2 = fgets($handle); // read second line
fclose($handle);
echo "Using fgets (line by line):\n" . $line1 . $line2;

// Using file
$lines = file('sample.txt');
echo "Using file (all lines):\n";
foreach ($lines as $line) {
    echo $line;
}

// Clean up sample file
unlink('sample.txt');
OutputSuccess
Important Notes

Always close files with fclose() after reading to free resources.

fread() reads bytes, so it may cut off in the middle of a line.

fgets() reads one line at a time, including the newline character.

Summary

Use fread() to read a specific number of bytes from a file.

Use fgets() to read a file line by line.

Use file() to read the whole file into an array of lines easily.