English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and Example of PHP file_get_contents() Function

PHP Filesystem Reference Manual

file_get_contents() can read a file into a string. This function is the preferred method for reading the content of a file into a string. If the operating system supports it, memory-mapped technology will also be used to enhance performance.

Syntax

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

This function is similar to the file() function, but the file_get_content() function returns the file as a string, starting from the specified offset and up to maxlen bytes.

Parameter

ParameterDescription
filenameRequired. Specifies the file to be read.
use_include_pathOptional. If you also want to search for files in use_include_path (in php.ini), set this parameter to '1‘.
contextOptional. Specifies the environment of the file handle. The context is a set of options that can modify the behavior of the stream. If NULL is used, it is ignored.
offsetOptional. Specifies the position in the file from which to start reading. This parameter is PHP 5.1 added.
maxlenOptional. Specifies the number of bytes to read. This parameter is PHP 5.1 added.

Example1

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

Output Result

www.oldtoolbag.com
w3codebox

Example2

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

Output Result

string(10)  "oldtoolbag.com"

PHP Filesystem Reference Manual