In PHP, the file_get_contents() function is one of the file handling functions available in this scripting language. This function reads the entire file source or part of it and returns it as PHP string data.
This is the most widely used function among other dedicated functions used for PHP file read. For example, file(), fread() and etc.
We should use file_get_contents() in PHP scripts, with the syntax as shown in the following code block.
<?php
file_get_contents(string $file_name, bool $use_include_path = false, resource $context, int $start = -1, int $limit);
?>
Now, let us have a look into the details on PHP file_get_contents() parameters.
Note:
Let us have two PHP programs for example getting entire file content and some portion of the content, respectively.
In this PHP example, we are going to use file_get_contents() function for reading the following HTML source saved as title_form.html. We have already seen this code with PHP HTML embedding example.
<html>
<head>
<title>Importing HTML</title>
</head>
<body>
<form name="frmTitle">
<tr>
<td>Title</td>
<td><input type="text" name="title" /> <input type="submit"
value="Submit" /></td>
</tr>
<tr>
</form>
</body>
</html>
Now, see the following PHP program for reading this source as a string output to be displayed with browsers.
<?php
$file_name = "title_form.html";
$file_content = file_get_contents($file_name);
echo $file_content . "<br/>";
/* Printing file content including HTML tags */
$html_content = str_replace("<", "<", $file_content);
$html_content = str_replace(">", ">", $html_content);
$html_content = str_replace("\r\n", "<br/>", $html_content);
echo $html_content;
?>
The first echo statement will display the output of the HTML file by displaying the form input field with a submit button. And, we are using PHP string replacements to replace the HTML tag symbol(angled bracket) with its appropriate HTML entities.
And, we have also replaced carriage return escape sequences with HTML line breaks to display file content with good readability.
Now, we are going to get some portion of file content by specifying the start and end limit for PHP file_get_Contents function.
<?php
$file_name = "title_form.html";
$head_content = file_get_contents($file_name, FALSE, NULL, 7, 48);
printHTMLContent($head_content);
$form_content = file_get_contents($file_name, FALSE, NULL, 62, 157);
printHTMLContent($form_content);
/* Printing file content including HTML tags */
function printHTMLContent($content)
{
$content = str_replace("<", "<", $content);
$content = str_replace(">", ">", $content);
$content = str_replace("\r\n", "<br/>", $content);
echo $content . "<br/>";
}
?>
Using this program, we can get HTML HEAD portion and FORM content by setting the start and end limit for the file_get_contents() function.
Cautions
Download PHP file_get_contents() Source Code
sir in crop image in php tutorial how to save croped image in folder or how to move croped image in folder