The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.
The path of the file to be read is sent as a parameter to the function and it returns the data read on success and FALSE on failure.
Syntax:
file_get_contents($path, $include_path, $context, $start, $max_length)
Parameters: The file_get_contents() function in PHP accepts one mandatory parameter and four optional parameters.
- $path: It specifies the path of the file or directory you want to check.
- $include_path: It is an optional parameter which searches for a file in the file in the include_path (in php.ini) also if it is set to 1.
- $context: It is an optional parameter which is used to specify a custom context.
- $start: It is an optional parameter which is used to specify the starting point in the file for reading.
- $max_length: It is an optional parameter which is used to specify the number of bytes to be read.
Return Value: It returns the read data on success and FALSE on failure.
Errors And Exception:
- If you want to open a file with special characters, such as spaces, it needs to be encoded first using urlencode().
- The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
- An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.
Examples:
br>Input: file_get_contents('https://tutorialspoint.dev/slugresolver/'); Output: A computer science portal for geeks Input: file_get_contents('gfg.txt', FALSE, NULL, 0, 14); Output: A computer science portal for geeks
Below programs illustrate the file_get_contents() function.
Program 1:
<?php // reading contents from the // geeksforgeeks homepage $homepage = file_get_contents ("https: //www.geeks forgeeks.org/"); echo $homepage ; ?> |
Output:
A computer science portal for geeks
Program 2:
<?php // reading 36 bytes startig from // the 0th character from gfg.txt $text = file_get_contents ( 'gfg.txt' , FALSE, NULL, 0, 36); echo $text ; ?> |
Output:
A computer science portal for geeks
Reference:
http://php.net/manual/en/function.file-get-contents.php
leave a comment
0 Comments