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 в Прил. M.

Внимание

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



file_get_contents
richard dot quadling at bandvulc dot co dot uk
15-Nov-2005 02: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.

<?php

// Define a context for HTTP.
$aContext = array(
  
'http' => array(
      
'proxy' => 'tcp://127.0.0.1:8080', // 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);

echo
$sFile;
?>

Hopefully this helps SOMEONE!!!
aidan at php dot net
30-Jan-2005 11: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:

http://pear.php.net/package/PHP_Compat

<file_existsfile_put_contents>
 Last updated: Mon, 14 Nov 2005