PHP file_get_contents

Summary: in this tutorial, you will learn how to use the PHP file_get_contents() function to read the entire file into a string.

Introduction to the PHP file_get_contents() function

The file_get_contents() function reads the entire file into a string. Here’s the syntax of the file_get_contents() function:

file_get_contents ( string $filename , bool $use_include_path = false , resource $context = ? , int $offset = 0 , int $maxlen = ? ) : string|false
Code language: PHP (php)

The file_get_contents() function has the following parameters:

  • $filename is the name of the file to read.
  • $use_include_path if you set it to true, the function will also search for the file in the include path.
  • $context specifies a valid context resource or null if don’t use a custom context.
  • $offset is the offset where the function starts reading on the original stream. If it is negative, the offset counts from the end of the stream.
  • $maxlen specifies the maximum length of data to read. By default, the function reads data till the end of the file.

The file_get_contents() returns the file contents on success or false on failure.

PHP file_get_contents() function examples

Let’s take some examples of using the file_get_contents() function.

1) Using the file_get_contents() function to download a webpage example

The following example shows how to use the file_get_contents() function to download an entire webpage into a string:

<?php $html = file_get_contents('https://www.php.net/'); echo $html;
Code language: HTML, XML (xml)

2) Using the file_get_contents() function to read an entire file into a string example

The following example uses the file_get_contents() to read the data from the readme.txt into a string:

<?php $filename = 'readme1.txt'; if (!is_readable($filename)) { die('File does not exist or is not readable'); } echo file_get_contents($filename);
Code language: HTML, XML (xml)

How it works.

  • First, throw an exception if the file exists or readable using the is_readable() function.
  • Second, read the entire file into a string and show its contents.

3) Using the file_get_contents() function to read a part of a file into a string

The following example uses the file_get_contents() function to read 20 characters starting from the 5th character in the readme.txt file:

<?php $filename = 'readme.txt'; if (!is_readable($filename)) { die('File does not exist or is not readable'); } echo file_get_contents($filename, null, null, 10, 20);
Code language: HTML, XML (xml)

In PHP 8, you can use the name arguments when calling the file_get_contents() function as follows:

$content = file_get_contents( $filename = $filename, $offset = 5, $maxlen = 20 );
Code language: PHP (php)

Summary

  • Use the PHP file_get_contents() function to read a file into a string.
Did you find this tutorial useful?