PHP | file_get_contents() Function

PHP file_get_contents() Function


Hello dear readers! welcome back to another edition of our tutorial on PHP. In this tutorial guide, we are going to be discussing about the PHP file_get_contents() Function.

The built-in PHP file_get_contents() function reads a file into a string. This PHP function is the preferred method to read the contents of a file into a string because it can use the memory mapping techniques if this is supported by the server to enhance performance.

Syntax

Following below is the syntax to use this function -

string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )


This is similar to the file() function except that the file_get_contents() function returns the file in a string starting at a specified offset.

Return Value

This PHP function returns the file in a string starting at a specified offset.

Example1

Try out the below example -

<?php
   $file = file_get_contents("/PhpProject/sample.txt", true);
   echo $file;
?>

Output

When the above code is executed, it will produce the following result -

webdesigntutorialz
webdesign

Example2
Try out the below example -

  <?php
   $section = file_get_contents("/PhpProject/sample.txt", NULL, NULL, 4, 10);
   var_dump($section);
?>

Output
When the above code is executed, it will produce the following result -

string(10) "esigntutor"


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about the PHP file_put_contents() Function.

Do feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.