file_get_contents

(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_get_contents can do a POST, create a context for that first:

<?php

$opts 
= array('http' =>
  array(
   
'method'  => 'POST',
   
'header'  => "Content-Type: text/xml\r\n".
     
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
   
'content' => $body,
   
'timeout' => 60
 
)
);
                       
$context  stream_context_create($opts);
$url 'https://'.$https_server;
$result file_get_contents($urlfalse$context, -140000);

?>
2012-04-16 15:17:20
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
I'm not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> ""
>>> file_get_contents($path, false, null, 5, 5)
=> "r/bin"
2021-07-28 00:11:34
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
Автор:
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
2021-08-24 22:53:54
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null){
    if(!file_exists($path)) return false;
    $size=filesize($path);
    if($start<0) $start+=$size;
    if($length===null) $length=$size-$start;
    return file_get_contents($path, false, null, $start, $length );
}
2021-09-14 06:22:30
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
Автор:
There's barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you're expecting an image you can do this:

<?php
$data 
file_get_contents('https://example.net/some-link');

$mimetype null;
foreach (
$http_response_header as $v) {
    if (
preg_match('/^content\-type:\s*(image\/[^;\s\n\r]+)/i'$v$m)) {
       
$mimetype $m[1];
    }
}

if (!
$mimetype) {
   
// not an image
}
2022-09-20 15:54:04
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
2023-03-16 18:20:42
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
To prevent mixed content most browsers/functions will use the protocol already used if you specify only // instead of http:// or https://. This is not the case with file_get_contents. You must specify the protocol. 

This does not work:
<?php
$jsonData 
file_get_contents('//example.com/file.json');
print 
$jsonData;
?>

Specifying only 'example.com/file.json' without the double slash does not work either.

When running on Apache 2.4 , using $_SERVER['REQUEST_SCHEME'] is a better way to be protocol agnostic.
<?php
$jsonData 
file_get_contents($_SERVER['REQUEST_SCHEME'].'://example.com/file.json');
print 
$jsonData;
?>

If using another web server, you may have to get the protocol another way or hard code it.
2023-08-08 13:55:43
http://php5.kiev.ua/manual/ru/function.file-get-contents.html
Автор:
If doing a negative offset to grab the end of a file and the file is shorter than the offset, then file_get_contents( ) will return false.

If you want it to just return what is available when the file is shorter than the negative offset, you could try again.

For example...

$contents = file_get_contents( $log_file, false, null, -4096 ); // Get last 4KB

if ( false === $contents ) {
    // Maybe error, or maybe file less than 4KB in size.

    $contents = file_get_contents( $log_file, false, null );

    if ( false === $contents ) {
        // Handle real error.
    }
}
2023-11-29 03:58:14
http://php5.kiev.ua/manual/ru/function.file-get-contents.html

    Поддержать сайт на родительском проекте КГБ