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 stringfopen()+fread()— stream-based readingfile()— 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
- Reading Files with PHP
- Writing and Appending to Files
- Working with Directories
- Handling File Uploads