PHP file_get_contents() Function
In this chapter you will learn:
- Definition for PHP file_get_contents() Function
- Syntax for PHP file_get_contents() Function
- Parameter for PHP file_get_contents() Function
- Return for PHP file_get_contents() Function
- Note for PHP file_get_contents() Function
- Example - Read text file
Definition
file_get_contents() takes the filename to open. It returns the contents of the file as a string, complete with new line characters \n where appropriate.
The file_get_contents() reads a file into a string.
Syntax
PHP file_get_contents() Function has the following syntax.
file_get_contents(path,include_path,context,start,max_length)
Parameter
Parameter | Is Required | Description |
---|---|---|
path | Required. | File to read |
include_path | Optional. | Set to '1' to search for the file in the include_path defined in php.ini |
context | Optional. | Context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL. |
start | Optional. | Where in the file to start reading. |
max_length | Optional. | How many bytes to read. |
Return
The function returns the read data or FALSE on failure.
Note
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
Use the === operator for testing the return value of this function.
Example
<?PHP//from ja v a 2 s . c om
$filename = "test.txt";
$filestring = file_get_contents($filename);
if ($filestring) {
print $filestring;
} else {
print "Could not open $filename.\n";
}
echo file_get_contents("test.txt");
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP file_put_contents() Function
- Syntax for PHP file_put_contents() Function
- Parameter for PHP file_put_contents() Function
- Return for PHP file_put_contents() Function
- Note for PHP file_put_contents() Function
- Example - Write to a file
Home » PHP Tutorial » PHP File Functions