File Get Content Function in PHP

Introduction

This article explains the File_Get_Content() function in PHP. The File_Get_Content() function reads an entire file into a string because it will use memory mapping techniques, if this is supported by the server. This function is the same as the file() function. This function is very important to us.

Syntax

file_get_contents(path,include_path,context,start,maxlength);

 

Parameter Description
filename Provide a name of the file name to read.
use_include_path File_use_include_path can be used to path search.
context Valid context resource created with stream_context_create() function. If you don't need to use a custom context, You can skip this parameter by providing NULL.
offset The offset to start reading at.
maxlength Maximum length of the data to read.

This function returns the data read on success otherwise returns false.

Example

Use of this example. You can see the home page of any website as in the following:

<?php

$get_homepage = file_get_contents('http://www.csharpcorner.com/');

echo $get_homepage;

?>

Output

cal1.jpg

This example shows searching within an include path:

<?php

$Search_file = file_get_contents('./cal.php', true);

$Search_file = file_get_contents('./cal.php', FILE_USE_INCLUDE_PATH);

?>

Example

This example shows reading a section of a file:

<?php

// read character 14

$read_f = file_get_contents('./cal.php', NULL, NULL, 20, 14);

var_dump($read_f);

?>

Output

cal.jpg

Example

This example shows use of stream contexts:

<?php

//stream creation

$arr = array(

  'http'=>array(

    'method'=>"GET",

    'header'=>"Accept-language: en\r\n" .

              "Cookie: foo=bar\r\n"

  )

);

 

$S_cont = stream_context_create($arr);

// Open the file using the HTTP headers set above

$files = file_get_contents('http://www.csharpcorner.com/', false, $S_cont);

?>

Up Next
    Ebook Download
    View all
    Learn
    View all