file_get_contents() is the simplest choice when the entire file can comfortably fit in memory. It returns false on failure, so use a strict comparison before working with the result.
$file = __DIR__ . '/data.txt';
$content = file_get_contents($file);
if ($content !== false) {
echo nl2br(htmlspecialchars($content));
}The examples below show additional variations and practical file-handling cases.
$str="my_file.txt"; // Change the path ( end of this page copy the file )
echo file_get_contents($str,1,null,0,120);
Output is here
Welcome to plus2net, Read PHP section here
file_get_contents return the output of a file as a string.
file_get_contents($filename, $useIncludePath = false, $context = null, $offset = 0, $length = null);
path:include_p:context:offset:length:$v1=urlencode('Alex John');
$str="http://127.0.0.1/t/file/file_get_contents-demo.php?name=$v1";
echo $str;
echo "<hr>";
echo file_get_contents($str,1,null,0,20);
Here is the second file where we will read the output file_get_contents-demo.php.
<?Php
$v1 = filter_input(INPUT_GET, 'name', FILTER_UNSAFE_RAW) ?? '';
echo 'Welcome ' . htmlspecialchars($v1, ENT_QUOTES, 'UTF-8');
?>
Output: here we are not getting the source code , only the output as returned by the browser is read as string and displayed.
Welcome Alex John
You can change the output by changing the start and max_length optional parameters of the function.
file_get_contents() can fetch remote URLs when URL wrappers are enabled. Do not pass an arbitrary user-supplied URL: that can create SSRF exposure to internal hosts or cloud metadata services. Prefer a fixed/allowlisted destination and keep TLS verification enabled.
Welcome to plus2net
Read PHP section here
<?php
// Set the specific AMFI scheme code
$schemeCode = "120847";
$apiUrl = "https://api.mfapi.in/mf/" . $schemeCode . "/latest";
// Use the default HTTPS verification. Add a timeout for the request.
$context = stream_context_create([
'http' => ['timeout' => 10],
]);
// Fetch the JSON response
$jsonResponse = file_get_contents($apiUrl, false, $context);
$data = json_decode($jsonResponse, true);
if (isset($data['data'][0]['nav'])) {
$fundName = $data['meta']['scheme_name'];
$navValue = $data['data'][0]['nav'];
$navDate = $data['data'][0]['date'];
echo "Fund: " . $fundName . " | NAV: " . $navValue . " (as of " . $navDate . ")";
} else {
echo "Error: Scheme data not found.";
}
?>
Reading external url by curl Reading a file by fread()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.