file_get_contents() function in PHP


The file_get_contents() function reads entire file into a string. The file() function reads the entire file in a array, whereas file_get_contents() function reads the entire file into a string.

Syntax

file_get_contents(file_path, flags, context, start_offset, max_length)

Parameters

  • file_path − The path of the file.

  • flags − The value of flags can be any combination of the following flags joined with the binary OR (|) operator.

    • FILE_USE_INCLUDE_PATH − Search for filename in the include directory.

    • FILE_TEXT − If unicode semantics are enabled, the default encoding of the read data is UTF-8. his flag cannot be used with FILE_BINARY.

    • FILE_BINARY − With this flag, the file is read in binary mode. This is the default setting and cannot be used with FILE_TEXT.

  • context − Context resource created with stream_context_create().

  • start_offset − Set the start point in the file for reading.

  • max_length − The Maximum length of data to be read. The default is to read until end of file is reached.

Return

The file_get_contents() function returns the data to be read. It returns false on failure.

Let’s say we have a file “info.txt” with the following content.

The U.S. is a country of 50 states.

Example

<?php
   $info = file_get_contents('info.txt',FALSE, NULL, 0, 50);
   echo $info;
?>

Output

The U.S. is a country of 50 states.

Let us see another example wherein we will read content from the homepage of a website.

Example

<?php
   $website = file_get_contents("https://www.qries.com");
   echo $website;
?>

Output

Sharing Knowledge

Updated on: 24-Jun-2020

608 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements