Understanding PHP's file_get_contents() Function: Syntax, Parameters, Return Values, and Usage Examples
The article explains PHP's file_get_contents() function, detailing its syntax, each parameter and the return value, and provides practical examples for reading local files, remote files, URLs, and using stream contexts for advanced file access.
The file_get_contents() function is a widely used PHP built‑in that reads the entire contents of a file into a string, supporting local files, remote files, and URLs.
Syntax of file_get_contents()
<code>string file_get_contents(string $filename, bool $use_include_path = false, resource $context = null, int $offset = 0, int $maxlen = null)</code>Parameters and Return Value
$filename : Path or URL of the file to read.
$use_include_path : Optional boolean; if true, the include_path is searched.
$context : Optional stream context resource for advanced operations.
$offset : Optional integer indicating the start position (default 0).
$maxlen : Optional integer limiting the number of bytes to read (default null, meaning the whole file).
The function returns the file contents as a string.
Usage Examples
1. Reading a Local File
Provide the file path as the first argument:
<code><?php
$filename = 'test.txt';
$file_content = file_get_contents($filename);
echo $file_content;
?></code>2. Reading a Remote File
Pass the remote file URL:
<code><?php
$url = 'https://example.com/test.txt';
$file_content = file_get_contents($url);
echo $file_content;
?></code>3. Reading a URL's HTML Content
Use the URL directly to fetch HTML:
<code><?php
$url = 'https://example.com';
$html = file_get_contents($url);
echo $html;
?></code>4. Using a Stream Context for Advanced Requests
Create a context (e.g., to add HTTP headers) and pass it as the third argument:
<code><?php
$context = stream_context_create([
'http' => [
'header' => 'Authorization: Basic ' . base64_encode('username:password')
]
]);
$url = 'https://example.com';
$html = file_get_contents($url, false, $context);
echo $html;
?></code>Summary
The file_get_contents() function offers a convenient way to read file data into a string, supporting various sources and optional parameters for include paths, offsets, length limits, and custom stream contexts, making it suitable for many backend PHP tasks.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.