PHP Read File Tutorial

Introduction

If you are just starting with PHP, you will quickly discover that working with files is one of the most practical skills you can learn. Almost every real-world PHP application needs to read data from somewhere — and files are one of the most common sources of that data.

Think about it this way. A website might store its settings in a configuration file. A server might write error logs to a text file. A user might upload a CSV file that your PHP script needs to process. In all of these situations, PHP needs to open a file and read what is inside it.

The good news is that PHP makes file reading very straightforward. It provides several built-in functions to handle different situations — from reading an entire file in one line to reading it slowly line by line for memory efficiency.

In this tutorial, we will go through each method step by step, with clear examples and plain English explanations. By the end, you will know exactly which method to use and when.

What You’ll Learn

  • How to read files using different PHP functions
  • When to use file_get_contents() vs fgets()
  • How to handle large files efficiently
  • Real-world log file example
  • Common mistakes and security tips

Why Read Files in PHP?

You may need to read files for:

  • Displaying text content
  • Reading configuration files
  • Loading logs
  • Processing uploaded files
  • Fetching stored data

Reading files is essential in real-world PHP applications.

Using fopen() and fread()

The fopen() function opens a file, and fread() reads its content.

Example

$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);

echo $content;

Explanation

  • fopen() opens the file in read mode
  • filesize() gets the file size
  • fread() reads the file content
  • fclose() closes the file

After running this code, your browser will display the full content of your example.txt file. For example, if your file contains:

Hello, this is line one.
This is line two.
This is line three.

Then the output will be:

Hello, this is line one. This is line two. This is line three.

Using file_get_contents() (Recommended)

The file_get_contents() function reads the entire file in one line.

Example

$content = file_get_contents("example.txt");
echo $content;

If your example.txt contains:

Welcome to Div PHP Tutorials.
Learn PHP step by step.

Then the output will be:

Welcome to Div PHP Tutorials. Learn PHP step by step.

Why Use This?

  • Simple and clean
  • No need to open or close the file manually
  • Best for small to medium files

Reading Files Line by Line (fgets)

To read a file line by line, use fgets().

Example

$file = fopen("example.txt", "r");

while (!feof($file)) {
    echo fgets($file) . "<br>";
}

fclose($file);

This is useful for large files.

If your example.txt contains three lines, the output will be:

Hello, this is line one.
This is line two.
This is line three.

Each line is printed on a new line in the browser because of the <br> tag added after each fgets() call.

Checking If a File Exists

Always check before reading a file.

Example

if (file_exists("example.txt")) {
    echo file_get_contents("example.txt");
} else {
    echo "File not found.";
}

This prevents errors and warnings.

💡 Why use this instead of file_get_contents()?

When a file is very large — for example, a log file with thousands of entries — loading the entire file into memory at once can slow down or crash your server. Reading line by line with fgets() processes one line at a time, keeping memory usage low.

Reading Files Using readfile()

The readfile() function outputs file content directly.

Example

readfile("example.txt");

Use this when you don’t need to process the content.

Comparison — Which Method Should You Use?

With four different ways to read a file in PHP, beginners often ask — which one should I use? Here is a simple comparison table to help you decide:

MethodBest ForOpens/Closes Manually?Memory Usage
file_get_contents()Small to medium files, quick readsNo — automaticMedium
fopen() + fread()When you need more control over readingYes — manualMedium
fgets()Large files, line-by-line processingYes — manualLow
readfile()Directly outputting file content to browserNo — automaticLow

Simple rule for beginners:

  • If you just need to read and display a file → use file_get_contents()
  • If the file is very large → use fgets()
  • If you just want to send a file to the browser → use readfile()
  • If you need full control over how much you read → use fopen() + fread()

Real-World Example: Building a Simple Log File Viewer

To bring everything together, let us build a practical real-world example — a simple log file viewer that reads and displays the last 10 lines of a log file.

This is the kind of feature you might build for a WordPress admin panel or a custom PHP dashboard.

Step 1: Create a sample log file

Create a file called app_log.txt and add some sample log entries:

[2026-01-01 09:00:01] User Alice logged in successfully.
[2026-01-01 09:15:22] User Bob failed login attempt.
[2026-01-01 09:30:45] New post published: "PHP Tutorial".
[2026-01-01 10:00:00] User Alice logged out.
[2026-01-01 10:15:10] Database backup completed.

Step 2: Read and display the log file safely

php

<?php
$logFile = __DIR__ . "/app_log.txt";

// Step 1 — Check if the log file exists
if (!file_exists($logFile)) {
    echo "<p>No log file found.</p>";
    exit;
}

// Step 2 — Read all lines into an array
$lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Step 3 — Get the last 10 lines only
$lastLines = array_slice($lines, -10);

// Step 4 — Display each line
echo "<h2>Application Log (Last 10 Entries)</h2>";
echo "<ul>";
foreach ($lastLines as $line) {
    echo "<li>" . htmlspecialchars($line) . "</li>";
}
echo "</ul>";
?>

Output:

Application Log (Last 10 Entries)
- [2026-01-01 09:00:01] User Alice logged in successfully.
- [2026-01-01 09:15:22] User Bob failed login attempt.
- [2026-01-01 09:30:45] New post published: "PHP Tutorial".
- [2026-01-01 10:00:00] User Alice logged out.
- [2026-01-01 10:15:10] Database backup completed.

Why this example is important:

  • It uses file() — a function that reads a file into an array, one line per element
  • It uses array_slice() to get only the last 10 entries — efficient and practical
  • It uses htmlspecialchars() to safely display the content — preventing XSS attacks
  • It uses __DIR__ for a reliable file path
  • It checks file existence before reading

This is real, production-level thinking applied to a beginner-friendly example.

Common Mistakes to Avoid

Mistake 1: Reading a File That Does Not Exist:
This is the most common mistake. If the file path is wrong or the file has been deleted, PHP will throw a warning and your script will fail. Always use file_exists(“example.txt”) to check if file exists or not.

Mistake 2: Forgetting to Close the File:
When you use fopen() to open a file, you must always close it with fclose() when you are done. Leaving files open wastes server resources and can cause unexpected behaviour in larger applications.

Mistake 3: Reading Very Large Files With file_get_contents():
file_get_contents() loads the entire file into memory at once. If you use it on a very large file — such as a server log with millions of lines — it can exhaust your server’s memory.

Mistake 4: Ignoring File Permissions:
PHP can only read a file if the server has permission to access it. If the file permissions are too restrictive, fopen() and other functions will fail silently or throw errors.

Security Tips

  • Never read user-specified files directly
  • Validate file paths
  • Restrict access to sensitive files
  • Avoid exposing configuration files

Summary

  • PHP provides multiple ways to read files
  • file_get_contents() is the easiest method
  • Use fgets() for large files
  • Always check file existence and permissions

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *