0PricingLogin
PHP Academy · Lesson

Reading Files with PHP

Read file contents using file_get_contents and fopen/fread.

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';
}

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