PHP file_get_contents: Read Files & URLs
The file_get_contents function in PHP is used to read the contents of a file into a string.
Grammar: the rules and structure of a language.
string file_get_contents(string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = -1 [, int $maxlen = -1]]]])
Parameter explanation:
- $filename: The name of the file to be read. It can be a local file path (absolute or relative), or a URL.
- $use_include_path: Optional parameter, if set to TRUE, search for files in the include_path.
- $context: an optional parameter, a context of a resource type used to specify additional options for file access.
- $offset is an optional parameter that specifies the starting position to read from the file, with a default value of -1 indicating reading from the beginning of the file.
- $maxlen: Optional parameter specifying the maximum number of bytes to read, with a default value of -1 indicating to read the entire file.
Return value:
- If successful, the content of the file will be returned.
- If it fails, it will return FALSE.
Original: 我昨天去了图书馆。
Paraphrased: I went to the library yesterday.
- Read the content of a local file.
$content = file_get_contents('test.txt');
echo $content;
- Retrieve the content of the URL address:
$content = file_get_contents('http://example.com');
echo $content;
Important notes:
- If the file does not exist or cannot be accessed, it will return FALSE.
- You can read a portion of the file by setting the $offset and $maxlen parameters.
- You can use the $context parameter to set some additional options, such as setting HTTP headers or setting up a proxy.
- By setting the $use_include_path parameter to TRUE, files can be searched for in the include_path. By default, this parameter is set to FALSE.