Reading a file sounds like a simple task, but the approach you choose can affect your code quality. In PHP projects, I have seen developers write custom file-reading logic for something that PHP already handles neatly with a built-in function.
The file_get_contents() function is one of the easiest ways to read the entire contents of a file into a string. It can also fetch data from URLs when URL wrappers are enabled, which makes it useful for working with APIs and remote resources.
In this article, we will see how to use file_get_contents() in PHP with practical examples, handle common errors, and understand when this function is the right choice.
What is file_get_contents() in PHP?
The PHP file_get_contents() function reads the complete contents of a file and returns the data as a string. The PHP file_get_contents() function reads the complete contents of a file and returns the data as a string. If you are working with different file operations in PHP, understanding the basics of PHP file handling will help you choose the right function for each task.
Unlike functions that read files line by line, file_get_contents() loads the complete content into memory at once. This makes it a convenient choice for small and medium-sized files where you need the entire data available immediately.
The basic syntax is:
$content = file_get_contents($filename);
The complete function details are available in the official PHP file_get_contents() documentation.
The function accepts a file path or URL as the first argument and returns:
- The file contents as a string when successful.
falsewhen the file cannot be read.
PHP file_get_contents() Syntax
The complete syntax of file_get_contents() is:
file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
): string|false
Here is what each parameter does:
| Parameter | Description |
|---|---|
$filename |
The file path or URL to read. |
$use_include_path |
Checks the PHP include path when set to true. |
$context |
A stream context containing additional options. |
$offset |
The position where reading should start. |
$length |
The maximum number of bytes to read. |
Most everyday use cases only require the first parameter.
Reading a Local File Using file_get_contents()
The most common use of file_get_contents() is reading a file stored on your server. You only need to provide the file path, and PHP will return the complete file content as a string.
For example, assume you have a text file named sample.txt in the same directory as your PHP file.
<?php
$content = file_get_contents("sample.txt");
echo $content;
?>
If sample.txt contains:
Welcome to PHP file handling.
The output will be:
Welcome to PHP file handling.
You can also provide an absolute or relative path:
<?php
$content = file_get_contents("/var/www/html/data/sample.txt");
echo $content;
?>
Handling file_get_contents() Errors
A common mistake is assuming that file_get_contents() always returns content. If the file does not exist or PHP does not have permission to read it, the function returns false.
Always check the return value when reading files from user input, external locations, or dynamic paths.
<?php
$file = "sample.txt";
$content = file_get_contents($file);
if ($content === false) {
echo "Unable to read the file.";
exit;
}
echo $content;
?>
Using a strict comparison with false is important. An empty file can return an empty string, which is different from a failed read operation.
Reading JSON Data Using file_get_contents()
A very common real-world use of file_get_contents() is reading JSON files. Many configuration files, API responses, and data exports use JSON format.
The function returns JSON as a string, which can then be converted into a PHP array or object using json_decode(). For more examples of encoding and decoding JSON data, see this JSON handling guide in PHP.
<?php
$json = file_get_contents("users.json");
$data = json_decode($json, true);
print_r($data);
?>
For example, if users.json contains:
{
"name": "John",
"email": "john@example.com"
}
The decoded PHP array will contain the JSON values:
Array
(
[name] => John
[email] => john@example.com
)
When working with JSON from external sources, validate the response before using the decoded data. A failed request can return invalid JSON, which may lead to unexpected results.
Using file_get_contents() to Read a URL
Apart from local files, PHP can also use file_get_contents() to fetch content from a URL. This is useful when consuming simple APIs or reading remote resources.
For URL access to work, the allow_url_fopen setting must be enabled in your PHP configuration.
You can check the related PHP configuration settings in the official PHP filesystem configuration documentation.
<?php
$response = file_get_contents("https://example.com");
echo $response;
?>
The above example sends a request to the URL and stores the response body as a string.
A typical use case is fetching JSON data from an API:
<?php
$url = "https://api.example.com/users";
$response = file_get_contents($url);
if ($response === false) {
echo "Unable to fetch API data.";
exit;
}
$data = json_decode($response, true);
print_r($data);
?>
For production applications, API calls usually need additional handling such as authentication headers, timeouts, and better error reporting. In those cases, using cURL may provide more control.
Reading Only a Part of a File
By default, file_get_contents() reads the complete file. However, you can use the $offset and $length parameters to read only a specific portion.
For example, the following code starts reading from the 10th byte and reads the next 50 bytes:
<?php
$content = file_get_contents(
"sample.txt",
false,
null,
10,
50
);
echo $content;
?>
This can be useful when working with large text files where loading everything into memory is unnecessary.
Using Stream Context with file_get_contents()
The optional stream context parameter allows you to customize how PHP handles the file or URL request.
For example, when making a POST request to a remote endpoint, you can create a context with request options.
<?php
$data = [
"name" => "John"
];
$options = [
"http" => [
"method" => "POST",
"header" => "Content-Type: application/json",
"content" => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents(
"https://example.com/api/users",
false,
$context
);
echo $response;
?>
Stream contexts are useful when you need more control over HTTP requests without switching to another library. The official PHP HTTP context options documentation lists available request options such as headers, methods, and error handling behaviour.
file_get_contents() vs fopen() and fread()
PHP provides multiple ways to read files. The right choice depends on how you need to process the data.
The file_get_contents() function is usually the simplest option when you need the complete file content at once. It handles opening, reading, and closing the file internally.
For example, this:
<?php
$content = file_get_contents("sample.txt");
echo $content;
?>
does the same basic job as manually opening and reading a file:
<?php
$file = fopen("sample.txt", "r");
$content = fread($file, filesize("sample.txt"));
fclose($file);
echo $content;
?>
The difference is control. The fopen() and fread() approach allows you to read data in smaller chunks, which is better when handling very large files.
| Method | Best suited for |
|---|---|
file_get_contents() |
Reading complete files, JSON files, and small API responses. |
fopen() with fread() |
Reading large files in controlled chunks. |
file() |
Reading a file into an array of lines. |
Common file_get_contents() Errors and Fixes
Although file_get_contents() is simple, a few errors appear frequently in real projects.
Failed to open stream: No such file or directory
This warning usually means the file path is incorrect.
Check the current working directory using:
<?php
echo getcwd();
?>
Using an absolute path or PHP’s __DIR__ constant can make file paths more reliable.
<?php
$content = file_get_contents(__DIR__ . "/sample.txt");
echo $content;
?>
Unable to open stream: Permission denied
This happens when the PHP process does not have permission to read the file.
Check the file permissions and make sure the web server user can access the file.
Unable to fetch remote URL
If reading a URL fails, check these common causes:
allow_url_fopenis disabled.- The remote server is unavailable.
- The request needs headers or authentication.
- The request is taking too long and needs a timeout.
For applications that depend on external APIs, consider using PHP cURL because it provides better control over request failures and response details.
Security Considerations When Using file_get_contents()
The file_get_contents() function itself is not dangerous. The security issues usually come from how the file path or URL is created.
Avoid passing user-controlled input directly into file_get_contents(). A user could provide an unexpected path and attempt to read files that should not be exposed.
For example, avoid code like this:
<?php
$file = $_GET["file"];
$content = file_get_contents($file);
echo $content;
?>
A safer approach is to control which files can be accessed and validate the input before reading.
<?php
$allowedFiles = [
"about.txt",
"terms.txt"
];
$file = $_GET["file"];
if (!in_array($file, $allowedFiles, true)) {
exit("Invalid file.");
}
$content = file_get_contents(__DIR__ . "/" . $file);
echo $content;
?>
When reading remote URLs, also avoid using user-provided URLs without validation. Applications that fetch arbitrary URLs can become vulnerable to server-side request forgery (SSRF) attacks.
When handling incoming JSON request data, PHP developers commonly use file_get_contents('php://input') before decoding the content. See this guide on receiving JSON POST data in PHP for a practical example.
Suppressing file_get_contents() Warnings
By default, PHP generates a warning when file_get_contents() cannot read a file. You may see this warning in your application output or logs.
The error suppression operator can hide the warning:
<?php
$content = @file_get_contents("missing-file.txt");
if ($content === false) {
echo "File could not be read.";
}
?>
Although this works, using @ is generally not recommended because it hides useful debugging information. A better approach is to handle the failure explicitly and log errors when required.
Checking If file_get_contents() Is Available
In most PHP installations, file_get_contents() is enabled by default. However, some hosting environments may disable URL access or restrict file operations.
You can check whether the function exists:
<?php
if (function_exists("file_get_contents")) {
echo "Function is available.";
} else {
echo "Function is not available.";
}
?>
For URL-based requests, check the allow_url_fopen configuration value:
<?php
if (ini_get("allow_url_fopen")) {
echo "URL access is enabled.";
} else {
echo "URL access is disabled.";
}
?>
Frequently Asked Questions
What does file_get_contents() do in PHP?
The PHP file_get_contents() function reads the complete contents of a file and returns the data as a string. If you work with different file operations in PHP, this PHP file handling guide explains related functions and concepts.
Can file_get_contents() read a URL?
Yes. It can read remote URLs when the allow_url_fopen PHP setting is enabled.
What is the difference between file_get_contents() and fread()?
file_get_contents() reads the entire content automatically, while fread() gives more control over how much data is read after opening a file with fopen().
Why does file_get_contents() return false?
It returns false when PHP cannot read the file or retrieve the requested resource. Common reasons include an incorrect path, missing permissions, or an unavailable URL.
Is file_get_contents() faster than fopen()?
For small and medium-sized files, file_get_contents() is usually the simpler and efficient choice. For very large files, reading data in chunks with fopen() and fread() can use less memory.
Conclusion
The PHP file_get_contents() function is a simple and practical way to read file contents, JSON data, and remote responses. For most everyday tasks, it removes the need to manually open, read, and close files.
The main things to remember are checking the return value, using safe file paths, and choosing another approach when you need more control over large files or complex HTTP requests.
Once you understand these basics, file_get_contents() becomes a useful tool for handling files and external data in PHP applications.
Can this function be used to pull data from a text file where the data is in one continuous line and the data is separated by a comma. I want the data to be listed in a column.
Yes, it can be done. file_get_contents() reads the file as a string, and you can use explode() to split the comma-separated values and display them line by line.
$data = file_get_contents(“data.txt”);
$items = explode(“,”, $data);
foreach ($items as $item) {
echo trim($item) . “
“;
}
For a normal-sized text file, this approach works well.