Current Location: Home> Latest Articles> PHP file_get_contents() Function Explained: How to Read File Contents into a String

PHP file_get_contents() Function Explained: How to Read File Contents into a String

M66 2025-06-19

Introduction to the file_get_contents() Function

In PHP development, it is often necessary to read the contents of a file and process it. To achieve this, you can use the built-in PHP function file_get_contents()

Parameter Explanations:

  • $filename: Required. The filename or URL to read. It can be a local file or a URL accessed via HTTP.
  • $use_include_path: Optional. If set to true, it will use the include path when opening the file. The default value is false.
  • $context: Optional. A stream context for HTTP requests. It can be used to send headers or modify the request. Default is null.
  • $offset: Optional. The offset at which to start reading the file. Default is -1, meaning it reads from the beginning of the file.
  • $maxlen: Optional. The maximum number of bytes to read. Default is null, meaning it reads the entire file.

Return Value:

If the file contents are successfully read, it returns the file content as a string. If the reading fails, it returns false.

Examples of Using file_get_contents()

Example 1: Reading a Local File

<?php
$filename = 'test.txt';
$content = file_get_contents($filename);
if ($content !== false) {
    echo "File contents: " . $content;
} else {
    echo "Failed to read the file!";
}
?>

Example 2: Reading a Remote File

<?php
$url = 'http://www.example.com/file.txt';
$content = file_get_contents($url);
if ($content !== false) {
    echo "File contents: " . $content;
} else {
    echo "Failed to read the file!";
}
?>

Example 3: Adding Request Headers When Reading a Remote File

<?php
$url = 'http://www.example.com/image.jpg';
$options = [
    'http' => [
        'header' => 'Authorization: Basic ' . base64_encode("username:password")
    ]
];
$context = stream_context_create($options);
$content = file_get_contents($url, false, $context);
if ($content !== false) {
    echo "File contents: " . $content;
} else {
    echo "Failed to read the file!";
}
?>

Conclusion

From the above examples, we can see the flexibility and powerful functionality of the file_get_contents() function in PHP. Whether it's reading local files, remote files, or adding request headers when accessing remote resources, file_get_contents() can easily handle these tasks.

We hope this article helps you better understand and master the use of the file_get_contents() function in PHP and makes your PHP development tasks easier.