0Pricing
PHP Academy · Lesson

Reading Files with PHP

Read file contents using file_get_contents and fopen/fread.

Reading Files with PHP is a free PHP Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

PHP and the File System

PHP can read, write, and manage files on the server's file system. Key functions for reading:

  • file_get_contents() — read entire file as string
  • fopen() + fread() — stream-based reading
  • file() — read file into an array of lines

file_get_contents()

The simplest way to read a file's entire content into a string:

<?php
$content = file_get_contents('/var/www/html/data.txt');

if ($content === false) {
    echo 'Could not read file';
} else {
    echo $content;
    echo strlen($content) . ' bytes';
}

Checking if File Exists

Always check before reading to avoid errors:

<?php
$path = '/var/data/config.json';

if (!file_exists($path)) {
    die('Config file not found');
}

if (!is_readable($path)) {
    die('No permission to read file');
}

$json = file_get_contents($path);
$config = json_decode($json, true);

file() — Read into Array

file() reads a file and returns each line as an array element:

<?php
$lines = file('data.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as $lineNum => $line) {
    echo ($lineNum + 1) . ': ' . $line . PHP_EOL;
}

fopen, fread, fclose

Low-level stream reading for large files — process without loading everything into memory:

<?php
$handle = fopen('large_file.txt', 'r');

if ($handle === false) die('Cannot open file');

// Read 1KB at a time
while (!feof($handle)) {
    $chunk = fread($handle, 1024);
    echo $chunk;
}

fclose($handle);

fgets for Line-by-Line

fgets() reads one line at a time — memory-efficient for large files:

<?php
$handle = fopen('server.log', 'r');

while (($line = fgets($handle)) !== false) {
    if (str_contains($line, 'ERROR')) {
        echo 'Found error: ' . $line;
    }
}

fclose($handle);

Reading Remote Files

file_get_contents() can also read from HTTP URLs if allow_url_fopen is enabled:

<?php
$json = file_get_contents('https://api.example.com/data.json');

// Prefer cURL for more control and error handling
$ch = curl_init('https://api.example.com/data.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

SplFileObject

SplFileObject provides an OO interface for file operations:

<?php
$file = new SplFileObject('data.txt', 'r');

foreach ($file as $lineNum => $line) {
    echo $lineNum . ': ' . $line;
}

// Read specific line:
$file->seek(5);
echo $file->current(); // line 6 (0-indexed)

Reading JSON Files

A common pattern: read and decode a JSON configuration file:

<?php
function loadJsonConfig(string $path): array {
    if (!file_exists($path)) {
        throw new RuntimeException("Config not found: $path");
    }
    $json = file_get_contents($path);
    $data = json_decode($json, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new RuntimeException('Invalid JSON: ' . json_last_error_msg());
    }
    return $data;
}

$cfg = loadJsonConfig('/app/config.json');

File Information

Get metadata about a file without reading its content:

<?php
$path = '/var/www/html/image.jpg';

echo filesize($path);           // bytes
echo filetype($path);           // 'file'
echo filemtime($path);          // last modified timestamp
echo date('Y-m-d', filemtime($path));

$info = pathinfo($path);
echo $info['dirname'];    // /var/www/html
echo $info['basename'];   // image.jpg
echo $info['extension'];  // jpg

Locking Files

Use file locking to prevent concurrent write conflicts:

<?php
$handle = fopen('counter.txt', 'r+');

if (flock($handle, LOCK_EX)) {  // exclusive lock
    $count = (int) fread($handle, 20);
    $count++;
    fseek($handle, 0);
    fwrite($handle, $count);
    fflush($handle);
    flock($handle, LOCK_UN);    // release
}

fclose($handle);

Quick Check

Which PHP function reads an entire file into a string in one call?

Recap: Reading Files

File reading essentials:

  • file_get_contents() — entire file as string
  • file() — file as array of lines
  • fopen/fread/fclose — stream for large files
  • fgets() — line-by-line stream reading
  • Always check file_exists and is_readable first
  • Use flock for concurrent access safety

Frequently asked questions

Is the “Reading Files with PHP” lesson free?

Yes — the full text of “Reading Files with PHP” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Reading Files with PHP”?

Read file contents using file_get_contents and fopen/fread. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Reading Files with PHP” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Files with PHP
  2. Writing and Appending to Files
  3. Working with Directories
  4. Handling File Uploads
← Back to PHP Academy