Главная | Руководство по MySQL | MySQL Manual | Документация к HTTP серверу Apache | Apache HTTP Server Documentation | downloads | faq

искать  Язык: Английский


(PHP 4 >= 4.3.0, PHP 5)

file_get_contentsПолучить содержимое файла в виде одной строки


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

Данная функция идентична функции file() с той только разницей, что содержимое файла возвращается в строке, начиная с указанного смещения offset и до maxlen байтов. В случае неудачи, file_get_contents() вернёт FALSE.

Использование функции file_get_contents() наиболее предпочтительно в случае необходимости получить содержимое файла целиком, поскольку для улучшения производительности функция использует алгоритм 'memory mapping' (если поддерживается операционной системой).

Замечание: Если вы открываете URI содержащий спецсимволы, такие как пробел, вам нужно закодировать URI при помощи urlencode().

Список изменений

Версия Описание
5.0.0 Добавлена поддержка контекста.
5.1.0 Добавлены аргументы offset и maxlen .


Замечание: Эта функция безопасна для обработки данных в двоичной форме.


Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция "fopen wrappers". Смотрите более подробную информацию об определении имени файла в описании функции fopen(), а также список поддерживаемых протоколов URL в List of Supported Protocols/Wrappers.


При использовании SSL, Microsoft IIS нарушает протокол, закрывая соединение без отправки индикатора close_notify. PHP сообщит об этом как о "SSL: Fatal Protocol Error" в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны установить error_reporting на уровень, исключающий E_WARNING. PHP версий 4.3.7 и старше умеет определять, что на стороне сервера находится проблемный IIS и не выводит предупреждение. Если вы используете fsockopen() для создания ssl:// сокета, вы сами отвечаете за определение и подавление этого предупреждения.

Смотрите также

  • file() - Читает содержимое файла и помещает его в массив
  • fgets() - Читает строку из файла
  • fread() - Бинарно-безопасное чтение файла
  • readfile() - Выводит файл
  • file_put_contents() - Записать строку в файл

User Contributed Notes
vlad dot wing at gmail dot com
27-Mar-2010 10:03
If you want to check if the function returned error, in case of a HTTP request an, it's not sufficient to test it against false. It may happen the return for that HTTP request was empty. In this case it's better to check if the return value is a bool.

if (
$result === false)
// treat error
} else {
// handle good case

[EDIT BY thiago: Has enhacements from an anonymous user]
rutger at webjin dot nl
14-Jan-2010 02:22
Sometimes you might get an error opening an http URL.
even though you have set "allow_url_fopen = On" in php.ini

For me the the solution was to also set "user_agent" to something.
ken at wetken dot net
28-Oct-2009 01:00
On Centos 5, and maybe other Red Hat based systems, any attempt to use file_get_contents to access a URL on an http  port other than 80 (e.g. "http://www.example.com:8040/page") may fail with a permissions violation (error 13) unless the box you are running php on has its seLinux set to 'permissive' not 'enforcing' . Otherwise the request doesn't even get out of the box, i.e. the permissions violation is generated locally by seLinux.
corey at effim dot com
09-Jun-2009 09:35
In my dev environment with a relatively low-speed drive (standard SATA 7200RPM) reading a 25MB zip file in 10 times...


= `cat /tmp/test.zip`;
// 1.05 seconds

$fh = fopen('/tmp/test.zip', 'r');
$data = fread($fh, filesize('/tmp/test.zip'));
// 1.31 seconds

$data = file_get_contents('/tmp/test.zip');
// 1.33 seconds


However, on a 21k text file running 100 iterations...


= `cat /tmp/test.txt`;
// 1.98 seconds

$fh = fopen('/tmp/test.txt', 'r');
$data = fread($fh, filesize('/tmp/test.txt'));
// 0.00082 seconds

$data = file_get_contents('/tmp/test.txt');
// 0.0069 seconds


Despite the comment about file_get_contents being faster do to memory mapping, file_get_contents is slowest in both of the above examples. If you need the best performance out of your production box, you might want to throw together a script to check out which method is fastest for what size files on that particular machine, then optimize your code to check the file size and use the appropriate function for it.
colnector bla-at_bla colnect.com
10-Aug-2008 09:34
A UTF-8 issue I've encountered is that of reading a URL with a non-UTF-8 encoding that is later displayed improperly since file_get_contents() related to it as UTF-8. This small function should show you how to address this issue:

function file_get_contents_utf8($fn) {
$content = file_get_contents($fn);
mb_convert_encoding($content, 'UTF-8',
mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
07-Aug-2008 12:34
if $filename has a relative path file_get_contents returns the uninterpreted sourcecode of the php-file with all comments etc.

I don't know whether this is a bug or intented or caused by server-configuration.

I think this behaviour should be included in the description of the function.
daniele dot ricci at staff dot dada dot net
05-Aug-2008 11:13
I recently upgraded my server to Slackware 12.0.

After this, a program of mine stopped working: the call to file_get_contents (to an URL served by a custom HTTP server) was returning false without generating any error!

After some investigations I saw this: my custom HTTP server closes the connection at the end of the content. This (without the header "Connection: close") seems to cause the problem I described.

To solve the problem I simply added that header to the answer of my custom HTTP server.
pascalxusPLEASENOSPAM at yahoo dot com
19-Jul-2008 12:17
if( false == ($str=file_get_contents( '../relative_path/test.txt' )))
    echo "Could not read file.";
    echo "File contents: $str";

  # Note: if the file cannot be opened then file_get_contents will attempt to warn the following:
  # Warning: file_get_contents(filename): failed to open stream
joachimb at gmail dot com
15-Apr-2008 09:38
Setting the timeout properly without messing with ini values:

= stream_context_create(array(
'http' => array(
'timeout' => 1
file_get_contents("http://example.com/", 0, $ctx);
3n1gm4 [at] gmail [dot] com
02-Apr-2008 09:12
This is a nice and simple substitute to get_file_contents() using curl, it returns FALSE if $contents is empty.

function curl_get_file_contents($URL)
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);

        if (
$contents) return $contents;
            else return

Hope this help, if there is something wrong or something you don't understand let me know :)
jose dot nobile at gmail dot com
29-Jan-2008 07:29
//PHP 4.2.x Compatibility function
if (!function_exists('file_get_contents')) {
file_get_contents($filename, $incpath = false, $resource_context = null)
          if (
false === $fh = fopen($filename, 'rb', $incpath)) {
trigger_error('file_get_contents() failed to open stream: No such file or directory', E_USER_WARNING);
          if (
$fsize = @filesize($filename)) {
$data = fread($fh, $fsize);
          } else {
$data = '';
              while (!
feof($fh)) {
$data .= fread($fh, 8192);
php [spat] hm2k.org
15-Jan-2008 11:58
I decided to make a similar function to this, called file_post_contents, it uses POST instead of GET to call, kinda handy...

function file_post_contents($url,$headers=false) {
$url = parse_url($url);

    if (!isset(
$url['port'])) {
      if (
$url['scheme'] == 'http') { $url['port']=80; }
      elseif (
$url['scheme'] == 'https') { $url['port']=443; }


$headers "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
"Host: ".$url['host'].$eol.
"Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
"Content-Type: application/x-www-form-urlencoded".$eol.
"Content-Length: ".strlen($url['query']).$eol.
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
$fp) {
fputs($fp, $headers);
$result = '';
feof($fp)) { $result .= fgets($fp, 128); }
      if (!
$headers) {
//removes headers
francois hill
03-Dec-2007 04:56
Seems file looks for the file inside the current working (executing) directory before looking in the include path, even with the FILE_USE_INCLUDE_PATH flag specified.

Same behavior as include actually.

By the way I feel the doc is not entirely clear on the exact order of inclusion (see include). It seems to say the include_path is the first location to be searched, but I have come across at least one case where the directory containing the file including was actually the first to be searched.

bearachute at gmail dot com
11-Jul-2007 09:38
If you're having problems with binary and hex data:

I had a problem when trying to read information from a ttf, which is primarily hex data. A binary-safe file read automatically replaces byte values with their corresponding ASCII characters, so I thought that I could use the binary string when I needed readable ASCII strings, and bin2hex() when I needed hex strings.

However, this became a problem when I tried to pass those ASCII strings into other functions (namely gd functions). var_dump showed that a 5-character string contained 10 characters, but they weren't visible. A binary-to-"normal" string conversion function didn't seem to exist and I didn't want to have to convert every single character in hex using chr().

I used unpack with "c*" as the format flag to see what was going on, and found that every other character was null data (ordinal 0). To solve it, I just did

str_replace(chr(0), "", $string);

which did the trick.

This took forever to figure out so I hope this helps people reading from hex data!
tobsn at php dot net
02-May-2007 04:26
you'll find the http response headers in: $http_response_header

Greg Ambrose (greg at catalina-it dot com dot au)
17-Apr-2007 04:37
[Editors note: As of PHP 5.2.1 you can specify `timeout` context option and pass the context to file_get_contents()]

The only way I could get get_file_contents() to wait for a very slow http request was to set the socket timeout as follows.

 ini_set('default_socket_timeout',    120);   
$a = file_get_contents("http://abcxyz.com");

Other times like execution time and input time had no effect.
siegfri3d at gmail dot com
05-Dec-2006 08:52
Use the previous example if you want to request the server for a special part of the content, IF and only if the server accepts the method.
If you want a simple example to ask the server for all the content, but only save a portion of it, do it this way:

This will echo the 20 first bytes of the google.com source code.
fcicqbbs at gmail dot com
04-Aug-2006 08:55
the bug #36857 was fixed.

Now you may use this code,to fetch the partial content like this:
=array('http' => array ('header'=> 'Range: bytes=1024-', ),);
$xcontext = stream_context_create($context);
that's all.
richard dot quadling at bandvulc dot co dot uk
15-Nov-2005 10:47
If, like me, you are on a Microsoft network with ISA server and require NTLM authentication, certain applications will not get out of the network. SETI@Home Classic and PHP are just 2 of them.

The workaround is fairly simple.

First you need to use an NTLM Authentication Proxy Server. There is one written in Python and is available from http://apserver.sourceforge.net/. You will need Python from http://www.python.org/.

Both sites include excellent documentation.

Python works a bit like PHP. Human readable code is handled without having to produce a compiled version. You DO have the opportunity of compiling the code (from a .py file to a .pyc file).

Once compiled, I installed this as a service (instsrv and srvany - parts of the Windows Resource Kit), so when the server is turned on (not logged in), the Python based NTLM Authentication Proxy Server is running.

Then, and here is the bit I'm really interested in, you need to tell PHP you intend to route http/ftp requests through the NTLM APS.

To do this, you use contexts.

Here is an example.


// Define a context for HTTP.
$aContext = array(
'http' => array(
'proxy' => 'tcp://', // This needs to be the server and the port of the NTLM Authentication Proxy Server.
'request_fulluri' => True,
$cxContext = stream_context_create($aContext);

// Now all file stream functions can use this context.

$sFile = file_get_contents("http://www.php.net", False, $cxContext);


Hopefully this helps SOMEONE!!!
aidan at php dot net
31-Jan-2005 07:23
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:


credits | contact