file_get_contents(): Reading file into a string

$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.
echo file_get_contents(path,include_p,context,offset,length);
path:
Required path to the file.
include_p:
Use FILE_USE_INCLUDE_PATH constant.
context:
A valid context resource
offset:
Starting point for reading, negative value means starting from end of file.
length:
Maximum length of data read

URL ( localhost) to get content

We will keep our function in one main file and try to read another file by sending request.
In second file we will keep minimum code to just return a welcome message with name. From our main file we will send the name by using GET method.

Here is a sample code to get output content from a file. While sending the request we will send name variable and try to get the welcome message with the name. We have used localhost for this. You should use your host or path in this code.
$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=$_GET['name']; // collect from url 
$v1=urldecode($v1);
echo "Welcome $v1";
?>
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.

Getting external URL content

This is a security risk to allow file_get_contents(). It can be used to get content from external URL if allow_url_fopen is set to On in php.ini file.

my_file.txt
Welcome to plus2net 
Read PHP section here

Reading external url by curl Reading a file by fread()

File Directory Functions
PHP
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer