(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP
file_get_contents — Reads entire file into a string
Description
file_get_contents(
string $filename
,
bool $use_include_path
= false
,
?resource $context
= null
,
int $offset
= 0,
?int $length
= null
): string|false
file_get_contents() is the preferred way to read the
contents of a file into a string. It will use memory mapping techniques if
supported by your OS to enhance performance.
Note:
If you’re opening a URI with special characters, such as spaces, you
need to encode the URI with urlencode().
Parameters
-
filename
-
Name of the file to read.
-
use_include_path
-
Note:
The
FILE_USE_INCLUDE_PATH
constant can be used
to trigger include path
search.
This is not possible if strict typing
is enabled, sinceFILE_USE_INCLUDE_PATH
is an
int. Usetrue
instead. -
context
-
A valid context resource created with
stream_context_create(). If you don’t need to use a
custom context, you can skip this parameter bynull
. -
offset
-
The offset where the reading starts on the original stream.
Negative offsets count from the end of the stream.Seeking (
offset
) is not supported with remote files.
Attempting to seek on non-local files may work with small offsets, but this
is unpredictable because it works on the buffered stream. -
length
-
Maximum length of data read. The default is to read until end
of file is reached. Note that this parameter is applied to the
stream processed by the filters.
Return Values
The function returns the read data or false
on failure.
Warning
This function may
return Boolean false
, but may also return a non-Boolean value which
evaluates to false
. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Errors/Exceptions
An E_WARNING
level error is generated if filename
cannot be found, length
is less than zero, or if seeking to the specified offset
in the stream fails.
When file_get_contents() is called on a directory,
an E_WARNING
level error is generated on Windows,
and as of PHP 7.4 on other operating systems as well.
Changelog
Version | Description |
---|---|
8.0.0 |
length is nullable now.
|
7.1.0 |
Support for negative offset s has been added.
|
Examples
Example #1 Get and output the source of the homepage of a website
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Example #2 Searching within the include_path
<?php
// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// Otherwise
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Example #3 Reading a section of a file
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>
The above example will output
something similar to:
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: enrn" .
"Cookie: foo=barrn"
)
);$context = stream_context_create($opts);// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
Notes
Note: This function is
binary-safe.
Tip
A URL can be used as a
filename with this function if the fopen wrappers have been enabled.
See fopen() for more details on how to specify the
filename. See the Supported Protocols and Wrappers for links to information
about what abilities the various wrappers have, notes on their usage,
and information on any predefined variables they may
provide.
Warning
When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify
indicator. PHP will report this as «SSL: Fatal
Protocol Error» when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP can detect buggy IIS server software when you open
the stream using the https://
wrapper and will suppress the
warning. When using fsockopen() to create an
ssl://
socket, the developer is responsible for detecting
and suppressing this warning.
See Also
- file() — Reads entire file into an array
- fgets() — Gets line from file pointer
- fread() — Binary-safe file read
- readfile() — Outputs a file
- file_put_contents() — Write data to a file
- stream_get_contents() — Reads remainder of a stream into a string
- stream_context_create() — Creates a stream context
- $http_response_header
Bart Friederichs ¶
10 years ago
file_get_contents can do a POST, create a context for that first:
<?php
$opts
= array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: text/xmlrn".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."rn",
'content' => $body,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);
?>
soger ¶
4 months ago
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/[^;snr]+)/i', $v, $m)) {
$mimetype = $m[1];
}
}
if (!
$mimetype) {
// not an image
}
Anonymous ¶
1 year ago
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)
453034559 at qq dot com ¶
1 year ago
//从指定位置获取指定长度的文件内容
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 );
}
allenmccabe at gmail dot com ¶
1 year ago
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"
I am trying to error handle the file_get_contents method so even if the user enters an incorrect website it will echo an error message rather then the unprofessional
Warning: file_get_contents(sidiowdiowjdiso): failed to open stream:
No such file or directory in C:xampphtdocstest.php on line 6
I thought if i make a try and catch it will be able to catch the error but that did not work.
try
{
$json = file_get_contents("sidiowdiowjdiso", true); //getting the file content
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
asked Apr 21, 2013 at 11:53
1
Try cURL with curl_error instead of file_get_contents:
<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
// Close handle
curl_close($ch);
?>
answered Apr 21, 2013 at 12:04
Andrey VolkAndrey Volk
3,4932 gold badges16 silver badges29 bronze badges
1
file_get_contents
do not throw an exception in error, instead it returns false, so you can check if the returned value is false:
$json = file_get_contents("sidiowdiowjdiso", true);
if ($json === false) {
//There is an error opening the file
}
This way you still get the warning, if you want to remove it, you need to put an @
in front of file_get_contents
. (This is considered a bad practice)
$json = @file_get_contents("sidiowdiowjdiso", true);
answered Apr 21, 2013 at 12:00
m4t1t0m4t1t0
5,6333 gold badges20 silver badges30 bronze badges
2
You could do any of the following:
Set a global error handler (that will handle WARNINGs as well), for all of your unhandled exceptions: http://php.net/manual/en/function.set-error-handler.php
Or by checking the return value of the file_get_contents function (with the === operator, as it will return boolean false on failure), and then manage the error message accordingly, and disable the error reporting on the function by prepending a «@» like so:
$json = @file_get_contents("file", true);
if($json === false) {
// error handling
} else {
// do something with $json
}
answered Apr 21, 2013 at 12:07
1
As a solution to your problem please try executing following code snippet
try
{
$json = @file_get_contents("sidiowdiowjdiso", true); //getting the file content
if($json==false)
{
throw new Exception( 'Something really gone wrong');
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
answered Apr 21, 2013 at 12:18
Rubin PorwalRubin Porwal
3,6311 gold badge23 silver badges26 bronze badges
5
Содержание
- file_get_contents
- Description
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- Handling I/O errors in PHP
- How file_get_contents fails
- Error handling in four steps
- Step 1: Detect that the file was not read
- Step 2: Suppress the warning
- Step 3: Get the reason for the failure
- Step 4: Add a fallback
- How not to handle errors
- Conclusion
- How to handle the warning of file_get_contents() function in PHP ?
- Хорошая обработка ошибок с file_get_contents
- Обновить
- 5 ответы
file_get_contents
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP
file_get_contents — Reads entire file into a string
Description
This function is similar to file() , except that file_get_contents() returns the file in a string , starting at the specified offset up to length bytes. On failure, file_get_contents() will return false .
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() .
Parameters
Name of the file to read.
The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int . Use true instead.
A valid context resource created with stream_context_create() . If you don’t need to use a custom context, you can skip this parameter by null .
The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.
Seeking ( offset ) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
Return Values
The function returns the read data or false on failure.
This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Errors/Exceptions
An E_WARNING level error is generated if filename cannot be found, length is less than zero, or if seeking to the specified offset in the stream fails.
When file_get_contents() is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.
Changelog
Version | Description |
---|---|
8.0.0 | length is nullable now. |
7.1.0 | Support for negative offset s has been added. |
Examples
Example #1 Get and output the source of the homepage of a website
Example #2 Searching within the include_path
Example #3 Reading a section of a file
The above example will output something similar to:
Example #4 Using stream contexts
// Create a stream
$opts = array(
‘http’ =>array(
‘method’ => «GET» ,
‘header’ => «Accept-language: enrn» .
«Cookie: foo=barrn»
)
);
$context = stream_context_create ( $opts );
// Open the file using the HTTP headers set above
$file = file_get_contents ( ‘http://www.example.com/’ , false , $context );
?>
Notes
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.
See Also
- file() — Reads entire file into an array
- fgets() — Gets line from file pointer
- fread() — Binary-safe file read
- readfile() — Outputs a file
- file_put_contents() — Write data to a file
- stream_get_contents() — Reads remainder of a stream into a string
- stream_context_create() — Creates a stream context
- $http_response_header
Источник
Handling I/O errors in PHP
This blog post is all about how to handle errors from the PHP file_get_contents function, and others which work like it.
The file_get_contents function will read the contents of a file into a string . For example:
You can try this out on the command-line like so:
This function is widely used, but I’ve observed that error handling around it is often not quite right. I’ve fixed a few bugs involving incorrect I/O error handling recently, so here are my thoughts on how it should be done.
How file_get_contents fails
For legacy reasons, this function does not throw an exception when something goes wrong. Instead, it will both log a warning, and return false .
Which looks like this when you run it:
Warnings are not very useful on their own, because the code will continue on without the correct data.
Error handling in four steps
If anything goes wrong when you are reading a file, your code should be throwing some type of Exception which describes the problem. This allows developers to put a try <> catch <> around it, and avoids nasty surprises where invalid data is used later.
Step 1: Detect that the file was not read
Any call to file_get_contents should be immediately followed by a check for that false return value. This is how you know that there is a problem.
This now gives both a warning and an uncaught exception:
Step 2: Suppress the warning
Warnings are usually harmless, but there are several good reasons to suppress them:
- It ensures that you are not depending on a global error handler (or the absence of one) for correct behaviour.
- The warning might appear in the middle of the output, depending on php.ini .
- Warnings can produce a lot of noise in the logs
Use @ to silence any warnings from a function call.
The output is now only the uncaught Exception :
Step 3: Get the reason for the failure
Unfortunately, we lost the “No such file or directory” message, which is pretty important information, which should go in the Exception . This information is retrieved from the old-style error_get_last method.
This function might just return empty data, so you should check that everything is set and non-empty before you try to use it.
This now embeds the failure reason directly in the message.
Step 4: Add a fallback
The last time I introduced error_clear_last() / get_last_error() into a code-base, I learned out that HHVM does not have these functions.
The fix for this is to write some wrapper code, to verify that each function exists.
This does the same thing as before, but without breaking other PHP runtimes.
Since HHVM is dropping support for PHP, I expect that this last step will soon become unnecessary.
How not to handle errors
Some applications put a series of checks before each I/O operation, and then simply perform the operation with no error checking. An example of this would be:
You could probably make a reasonable-sounding argument that checks are a good idea, but I consider them to be misguided:
- If you skip any actual error handling, then your code is going to fail in more surprising ways when you encounter an I/O problem that could not be detected.
- If you do perform correct error handling as well, then the extra checks add nothing other than more branches to test.
Lastly, beware of false positives. For example, the above snippet will reject HTTP URL’s, which are perfectly valid for file_get_contents .
Conclusion
Most PHP code now uses try / catch / finally blocks to handle problems, but the ecosystem really values backwards compatibility, so existing functions are rarely changed.
The style of error reporting used in these I/O functions is by now a legacy quirk, and should be wrapped to consistently throw a useful Exception .
Источник
How to handle the warning of file_get_contents() function in PHP ?
The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.
The path of the file to be read is sent as a parameter to the function and it returns the data read on success and FALSE on failure.
Return Value: It returns the read data on success and FALSE on failure.
Errors And Exception:
- If you want to open a file with special characters, such as spaces, it needs to be encoded first using urlencode().
- The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
- An E_WARNING level error is generated if filename cannot be found, max length is less than zero, or if seeking to the specified offset in the stream fails.
Examples:
Program 1:
Runtime Errors:
PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5
PHP Warning: file_get_contents(https://www.geeksforgeeks.org/): failed to open stream: php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5
Output:
Program 2:
Runtime Errors:
PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6
PHP Warning: file_get_contents(gfg.txt): failed to open stream: No such file or directory in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6
Output:
As clearly we can see above runtime errors in the form PHP Warning have occurred which were really unexpected. Here the questions arise of removing these errors, is there a way to handle these errors?
Yes, PHP provides us with a simple solution.
PHP supports one error control operator: the sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. So, above PHP Warning can be suppressed by simply inserting error control operator(@) before the function call file_get_contents() in the following way:
Источник
Хорошая обработка ошибок с file_get_contents
Я использую простой который имеет эту функцию:
Иногда URL-адрес может быть просто недействительным, и я хочу справиться с этим. Я думал, что могу использовать попытку и поймать, но это не сработало, поскольку оно не генерирует исключение, а просто выдает предупреждение php, подобное этому:
Строка 39 находится в приведенном выше коде.
Как я могу правильно обработать эту ошибку, могу ли я просто использовать простой if условие, не похоже, что оно возвращает логическое значение.
Спасибо всем за любую помощь
Обновить
Это хорошее решение?
почему он вызывается по URL, а не по имени файла? — Your Common Sense
Ну, это хороший вопрос, так что +1 — TheLQ
@Abs Вероятно, это потому, что вы без причины отрицаете все ответы. — NullUserException
@Abs (и Col): Как использование @ и кода возврата менее законно для «обработки ошибок», чем перехват исключения или решение, которое у вас есть в настоящее время в разделе «Хорошее ли это решение?». Только из-за @? — grossvogel
Предлагаемые сторонние альтернативы, которые фактически используют DOM вместо анализа строк: phpQuery, Зенд_Дом, QueryPath и FluentDom. — Gordon
5 ответы
В основном обертка для file_get_contents . Это вызовет исключение в случае сбоя. Чтобы не пришлось переопределять file_get_contents сам, ты можешь
Теперь вы можете:
Подавление ошибок (либо с помощью @ или понизив уровень error_reporting действительный решение. Это может вызывать исключения, и вы можете использовать это для обработки своих ошибок. Есть много причин, почему file_get_contents может генерировать предупреждения, и само руководство по PHP рекомендует снизить значение error_reporting: См. Руководство
ответ дан 07 авг.
Вы можете захватить вывод @file_get_contents. Если это === FALSE, вы можете создать свое собственное исключение, установить код возврата или что-то еще. — гроссфогель
@quantumSoup: имейте в виду, что ваш первый пример if(file_get. выдаст ошибку, если пустой файл будет успешно прочитан, тогда как второй if($contents === false) будет возвращать ошибку только в том случае, если ошибка действительно есть. — гроссфогель
@gross Да, я забыл проверить на идентичность с ложью в первом. Зато выкинул всю первую часть. — QuantumSoup
Странно, кажется, что file_get_contents не любит закодированные URL-адреса. Я удалил это, и, похоже, все работает нормально. — Abs
@Abs Действительно, вы не должны передавать закодированные URL-адреса какой-либо файловой функции PHP — QuantumSoup
Используйте CURL чтобы получить URL-адрес и обработать ответ об ошибке таким образом.
Простой пример из curl_init ():
ответ дан 07 авг.
Итак, идея состоит в том, чтобы сначала проверить URL-адрес, прежде чем передавать его в file_get_contents, я думаю, что это хорошая идея. Я думаю, что лучше использовать fopen. Смотрите мое обновление, что вы думаете? — Abs
Нет, CURL вернет вам содержимое, поэтому в последующем файле file_get_contents не будет необходимости. — Треффиннон
Я не могу использовать CURL или fopen для получения содержимого. Мне все еще нужно использовать file_get_contents, предоставляемый API, мне просто нужно проверить, не вернул ли file_get_contents ошибку, и что-то сделать, если она есть. Опять же, я не могу напрямую возиться с file_get_contents, поскольку он находится в API simplehtmldom, как я уже упоминал в своем вопросе. — Abs
+1 Используйте CURL там, где он доступен, для всех HTTP-запросов. Он для этого предназначен. file_get_contents будет работать (в большинстве случаев), но он не предназначен для HTTP, поэтому будет довольно сложно обнаружить определенные типы ошибок и т. д. — ircmaxell
С моей точки зрения, хорошая обработка ошибок — одна из самых больших проблем в PHP. К счастью, вы можете зарегистрировать свой собственный обработчик ошибок и сами решить, что делать.
Вы можете определить довольно простой обработчик ошибок следующим образом:
и зарегистрируйте его в своей функции следующим образом:
ответ дан 23 апр.
Чтобы понять, почему вызов file_get_contents мог потерпеть неудачу, вы можете просто использовать функцию php error_get_last:
ответ дан 20 авг.
ЕСЛИ вы загружаете данные с внешнего URL-адреса, наилучшей обработкой будет внедрение HTTP-библиотеки, такой как Zend_Http. Это не сильно отличается от использования CURL или fopen, за исключением того, что он будет извлекать сведения об этих «директорах» в универсальный API, а затем вы можете выбрать, что вы хотите использовать. Он также будет иметь некоторые встроенные ловушки ошибок, чтобы упростить вам задачу.
Если вам не нужны накладные расходы на другую библиотеку, вы можете закодировать ее самостоятельно, и в этом случае я всегда предпочитаю CURL.
ответ дан 07 авг.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками php error-handling or задайте свой вопрос.
Источник
This blog post is all about how to handle errors from the PHP file_get_contents
function, and others which work like it.
The file_get_contents
function will read the contents of a file into a string
. For example:
<?php
$text = file_get_contents("hello.txt");
echo $text;
You can try this out on the command-line like so:
$ echo "hello" > hello.txt
$ php test.php
hello
This function is widely used, but I’ve observed that error handling around it is often not quite right. I’ve fixed a few bugs involving incorrect I/O error handling recently, so here are my thoughts on how it should be done.
How file_get_contents fails
For legacy reasons, this function does not throw an exception when something goes wrong. Instead, it will both log a warning, and return false
.
<?php
$filename = "not-a-real-file.txt";
$text = file_get_contents($filename);
echo $text;
Which looks like this when you run it:
$ php test.php
PHP Warning: file_get_contents(not-a-real-file.txt): failed to open stream: No such file or directory in test.php on line 3
PHP Stack trace:
PHP 1. {main}() test.php:0
PHP 2. file_get_contents() test.php:3
Warnings are not very useful on their own, because the code will continue on without the correct data.
Error handling in four steps
If anything goes wrong when you are reading a file, your code should be throwing some type of Exception
which describes the problem. This allows developers to put a try {} catch {}
around it, and avoids nasty surprises where invalid data is used later.
Step 1: Detect that the file was not read
Any call to file_get_contents
should be immediately followed by a check for that false
return value. This is how you know that there is a problem.
<?php
$filename = "not-a-real-file.txt";
$text = file_get_contents($filename);
if($text === false) {
throw new Exception("File was not loaded");
}
echo $text;
This now gives both a warning and an uncaught exception:
$ php test.php
PHP Warning: file_get_contents(not-a-real-file.txt): failed to open stream: No such file or directory in test.php on line 3
PHP Stack trace:
PHP 1. {main}() test.php:0
PHP 2. file_get_contents() test.php:3
PHP Fatal error: Uncaught Exception: File was not loaded in test.php:5
Stack trace:
#0 {main}
thrown in test.php on line 5
Step 2: Suppress the warning
Warnings are usually harmless, but there are several good reasons to suppress them:
- It ensures that you are not depending on a global error handler (or the absence of one) for correct behaviour.
- The warning might appear in the middle of the output, depending on
php.ini
. - Warnings can produce a lot of noise in the logs
Use @
to silence any warnings from a function call.
<?php
$filename = "not-a-real-file.txt";
$text = @file_get_contents($filename);
if($text === false) {
throw new Exception("File was not loaded");
}
echo $text;
The output is now only the uncaught Exception
:
$ php test.php
PHP Fatal error: Uncaught Exception: File was not loaded in test.php:5
Stack trace:
#0 {main}
thrown in test.php on line 5
Step 3: Get the reason for the failure
Unfortunately, we lost the “No such file or directory” message, which is pretty important information, which should go in the Exception
. This information is retrieved from the old-style error_get_last
method.
This function might just return empty data, so you should check that everything is set and non-empty before you try to use it.
<?php
$filename = "not-a-real-file.txt";
error_clear_last();
$text = @file_get_contents($filename);
if($text === false) {
$e = error_get_last();
$error = (isset($e) && isset($e['message']) && $e['message'] != "") ?
$e['message'] : "Check that the file exists and can be read.";
throw new Exception("File '$filename' was not loaded. $error");
}
echo $text;
This now embeds the failure reason directly in the message.
$ php test.php
PHP Fatal error: Uncaught Exception: File 'not-a-real-file.txt' was not loaded. file_get_contents(not-a-real-file.txt): failed to open stream: No such file or directory in test.php:9
Stack trace:
#0 {main}
thrown in test.php on line 9
Step 4: Add a fallback
The last time I introduced error_clear_last()
/get_last_error()
into a code-base, I learned out that HHVM does not have these functions.
Call to undefined function error_clear_last()
The fix for this is to write some wrapper code, to verify that each function exists.
<?php
$filename = 'not-a-real-file';
clearLastError();
$text = @file_get_contents($filename);
if ($text === false) {
$error = getLastErrorOrDefault("Check that the file exists and can be read.");
throw new Exception("Could not retrieve image data from '$filename'. $error");
}
echo $text;
/**
* Call error_clear_last() if it exists. This is dependent on which PHP runtime is used.
*/
function clearLastError()
{
if (function_exists('error_clear_last')) {
error_clear_last();
}
}
/**
* Retrieve the message from error_get_last() if possible. This is very useful for debugging, but it will not
* always exist or return anything useful.
*/
function getLastErrorOrDefault(string $default)
{
if (function_exists('error_clear_last')) {
$e = error_get_last();
if (isset($e) && isset($e['message']) && $e['message'] != "") {
return $e['message'];
}
}
return $default;
}
This does the same thing as before, but without breaking other PHP runtimes.
$ php test.php
PHP Fatal error: Uncaught Exception: Could not retrieve image data from 'not-a-real-file'. file_get_contents(not-a-real-file): failed to open stream: No such file or directory in test.php:7
Stack trace:
#0 {main}
thrown in test.php on line 7
Since HHVM is dropping support for PHP, I expect that this last step will soon become unnecessary.
How not to handle errors
Some applications put a series of checks before each I/O operation, and then simply perform the operation with no error checking. An example of this would be:
<?php
$filename = "not-a-real-file.txt";
// Check everything!
if(!file_exists($filename)) {
throw new Exception("$filename does not exist");
}
if(!is_file($filename)) {
throw new Exception("$filename is not a file");
}
if(!is_readable($filename)) {
throw new Exception("$filename cannot be read");
}
// Assume that nothing can possibly go wrong..
$text = @file_get_contents($filename);
echo $text;
You could probably make a reasonable-sounding argument that checks are a good idea, but I consider them to be misguided:
- If you skip any actual error handling, then your code is going to fail in more surprising ways when you encounter an I/O problem that could not be detected.
- If you do perform correct error handling as well, then the extra checks add nothing other than more branches to test.
Lastly, beware of false positives. For example, the above snippet will reject HTTP URL’s, which are perfectly valid for file_get_contents
.
Conclusion
Most PHP code now uses try
/catch
/finally
blocks to handle problems, but the ecosystem really values backwards compatibility, so existing functions are rarely changed.
The style of error reporting used in these I/O functions is by now a legacy quirk, and should be wrapped to consistently throw a useful Exception
.
The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.
The path of the file to be read is sent as a parameter to the function and it returns the data read on success and FALSE on failure.
Return Value: It returns the read data on success and FALSE on failure.
Errors And Exception:
- If you want to open a file with special characters, such as spaces, it needs to be encoded first using urlencode().
- The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
- An E_WARNING level error is generated if filename cannot be found, max length is less than zero, or if seeking to the specified offset in the stream fails.
Examples:
Input: file_get_contents('https://www.geeksforgeeks.org/'); Output: A computer science portal for geeks Input: file_get_contents('gfg.txt', FALSE, NULL, 0, 14); Output: A computer science portal for geeks
Program 1:
Runtime Errors:
PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5
PHP Warning: file_get_contents(https://www.geeksforgeeks.org/): failed to open stream: php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5
Output:
It will redirect to GeeksforGeeks Home Page
Program 2:
PHP
<?php
$text
=
file_get_contents
(
'gfg.txt'
,
FALSE, NULL, 0, 36);
echo
$text
;
?>
Runtime Errors:
PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6
PHP Warning: file_get_contents(gfg.txt): failed to open stream: No such file or directory in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6
Output:
It will display the content of gfg.txt file. For Example: A computer science portal for geeks
As clearly we can see above runtime errors in the form PHP Warning have occurred which were really unexpected. Here the questions arise of removing these errors, is there a way to handle these errors?
Yes, PHP provides us with a simple solution.
PHP supports one error control operator: the sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. So, above PHP Warning can be suppressed by simply inserting error control operator(@) before the function call file_get_contents() in the following way:
Updated Program 1:
PHP
Output:
It will redirect to GeeksforGeeks Home Page
Updated Program 2:
PHP
<?php
$text
= @
file_get_contents
(
'gfg.txt'
,
FALSE, NULL, 0, 36);
echo
$text
;
?>
Output:
It will display the content of gfg.txt file. For Example: A computer science portal for geeks
So, after adding the ‘@’ symbol we can see that all those PHP warnings are suppressed and only output is displayed as above.
Reference: https://www.php.net/manual/en/language.operators.errorcontrol.php
file_get_contents
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
file_get_contents — Читает содержимое файла в строку
Описание
string file_get_contents
( string $filename
[, bool $use_include_path
= false
[, resource $context
[, int $offset
= -1
[, int $maxlen
]]]] )
Использование функции file_get_contents()
наиболее предпочтительно в случае необходимости получить
содержимое файла целиком, поскольку для улучшения производительности
функция использует технику отображения файла в память
(memory mapping), если она поддерживается вашей операционной системой.
Замечание:
Если вы открываете URI содержащий спецсимволы, такие как пробел,
вам нужно закодировать URI при помощи urlencode().
Список параметров
-
filename
-
Имя читаемого файла.
-
use_include_path
-
Замечание:
Начиная с версии PHP 5 можно использовать константу
FILE_USE_INCLUDE_PATH
для поиска файла
в include path. -
context
-
Корректный ресурс контекста, созданный с помощью функции
stream_context_create(). Если в использовании
особого контекста нет необходимости, можно пропустить этот параметр
передав в него значениеNULL
. -
offset
-
Смещение, с которого начнется чтение оригинального потока.
Поиск смещения (
offset
) не поддерживается при
работе с удаленными файлами. Попытка поиска смещения на нелокальных
файлах может работать при небольших смещениях, но этот
результат является непредсказуемым, так как он работает на
буферизованном потоке. -
maxlen
-
Максимальный размер читаемых данных. По умолчанию чтение
осуществляется пока не будет достигнут конец файла. Учтите, что
этот параметр применяется и к потоку с фильтрами.
Возвращаемые значения
Функция возвращает прочтенные данные или FALSE
в случае возникновения ошибки.
Внимание
Эта функция
может возвращать как boolean FALSE
, так и не-boolean значение,
которое приводится к FALSE
. За более подробной информацией обратитесь к разделу
Булев тип. Используйте оператор === для проверки значения,
возвращаемого этой функцией.
Ошибки
Будет сгенерирована ошибка уровня E_WARNING
, если
параметр filename
не удается найти,
параметр maxlength
меньше нуля или
поиск по смещению offset
в потоке завершается неудачно.
Примеры
Пример #1 Получить и вывести исходный код домашней страницы вебсайта
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Пример #2 Поиск файлов в include_path
<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Пример #3 Чтение секции файла
<?php
// Читаем 14 символов, начиная с 21 символа
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
Результатом выполнения данного примера
будет что-то подобное:
string(14) "lle Bjori Ro"
Пример #4 Использование потоковых контекстов
<?php
// Создаем поток
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: enrn" .
"Cookie: foo=barrn"
)
);$context = stream_context_create($opts);// Открываем файл с помощью установленных выше HTTP-заголовков
$file = file_get_contents('http://www.example.com/', false, $context);
?>
Список изменений
Версия | Описание |
---|---|
5.1.0 |
Добавлены аргументы offset иmaxlen .
|
Примечания
Замечание: Эта функция безопасна
для обработки данных в двоичной форме.
Подсказка
Для этой функции вы можете использовать URL
в качестве имени файла, если была включена опция fopen wrappers. Смотрите более
подробную информацию об определении имени файла в описании функции
fopen(). Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список
предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).
Внимание
При использовании SSL,
Microsoft IIS нарушает протокол, закрывая соединение без отправки
индикатора close_notify. PHP сообщит об этом как «SSL: Fatal Protocol Error»
в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны
установить error_reporting на
уровень, исключающий E_WARNING.
PHP версий 4.3.7 и старше умеет определять, что на стороне сервера находится
проблемный IIS при открытии потока с помощью обертки https:// и не выводит предупреждение.
Если вы используете fsockopen() для создания ssl:// сокета,
вы сами отвечаете за определение и подавление этого предупреждения.
Смотрите также
- file() — Читает содержимое файла и помещает его в массив
- fgets() — Читает строку из файла
- fread() — Бинарно-безопасное чтение файла
- readfile() — Выводит файл
- file_put_contents() — Пишет строку в файл
- stream_get_contents() — Читает оставшуюся часть потока в строку
- stream_context_create() — Создаёт контекст потока
- $http_response_header
Вернуться к: Файловая система
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
file_get_contents — Reads entire file into a string
Description
string file_get_contents
( string $filename
[, bool $use_include_path
= false
[, resource $context
[, int $offset
= 0
[, int $maxlen
]]]] )
file_get_contents() is the preferred way to read the
contents of a file into a string. It will use memory mapping techniques if
supported by your OS to enhance performance.
Note:
If you’re opening a URI with special characters, such as spaces, you
need to encode the URI with urlencode().
Parameters
-
filename
-
Name of the file to read.
-
use_include_path
-
Note:
As of PHP 5 the
FILE_USE_INCLUDE_PATH
constant can be used
to trigger include path
search. -
context
-
A valid context resource created with
stream_context_create(). If you don’t need to use a
custom context, you can skip this parameter byNULL
. -
offset
-
The offset where the reading starts on the original stream.
Seeking (
offset
) is not supported with remote files.
Attempting to seek on non-local files may work with small offsets, but this
is unpredictable because it works on the buffered stream. -
maxlen
-
Maximum length of data read. The default is to read until end
of file is reached. Note that this parameter is applied to the
stream processed by the filters.
Return Values
The function returns the read data or FALSE
on failure.
Warning
This function may
return Boolean FALSE
, but may also return a non-Boolean value which
evaluates to FALSE
. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Errors/Exceptions
An E_WARNING
level error is generated if filename
cannot be found, maxlength
is less than zero, or if seeking to the specified offset
in the stream fails.
Examples
Example #1 Get and output the source of the homepage of a website
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Example #2 Searching within the include_path
<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Example #3 Reading a section of a file
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
The above example will output
something similar to:
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: enrn" .
"Cookie: foo=barrn"
)
);$context = stream_context_create($opts);// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
Changelog
Version | Description |
---|---|
5.1.0 |
Added the offset andmaxlen parameters.
|
Notes
Note: This function is
binary-safe.
Tip
A URL can be used as a
filename with this function if the fopen wrappers have been enabled.
See fopen() for more details on how to specify the
filename. See the Supported Protocols and Wrappers for links to information
about what abilities the various wrappers have, notes on their usage,
and information on any predefined variables they may
provide.
Warning
When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify indicator. PHP will report this as «SSL: Fatal
Protocol Error» when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP can detect buggy IIS server software when you open
the stream using the https:// wrapper and will suppress the
warning. When using fsockopen() to create an
ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
See Also
- file() — Reads entire file into an array
- fgets() — Gets line from file pointer
- fread() — Binary-safe file read
- readfile() — Outputs a file
- file_put_contents() — Write a string to a file
- stream_get_contents() — Reads remainder of a stream into a string
- stream_context_create() — Creates a stream context
- $http_response_header
User Contributed Notes
Bart Friederichs
4 years ago
file_get_contents can do a POST, create a context for that first:
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: text/xmlrn".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."rn",
'content' => $body,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);
joachimb at gmail dot com
8 years ago
Setting the timeout properly without messing with ini values:
<?php
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
file_get_contents("http://example.com/", 0, $ctx);
?>
volkan-k at users dot sourceforge dot net
3 years ago
If you are using file_get_contents() function to retrieve HTTP url and printing HTTP content, you can also send original content-type header using $http_response_header and header() function;
<?phpforeach ($http_response_header as $value) {
if (preg_match('/^Content-Type:/i', $value)) {
// Successful match
header($value,false);
}
}?>
colnector bla-at_bla colnect.com
7 years ago
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:
<?php
function file_get_contents_utf8($fn) {
$content = file_get_contents($fn);
return mb_convert_encoding($content, 'UTF-8',
mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}
?>
Stas Trefilov, OpteamIS
5 years ago
here is another (maybe the easiest) way of doing POST http requests from php using its built-in capabilities. feel free to add the headers you need (notably the Host: header) to further customize the request.
note: this method does not allow file uploads. if you want to upload a file with your request you will need to modify the context parameters to provide multipart/form-data encoding (check out http://www.php.net/manual/en/context.http.php ) and build the $data_url following the guidelines on http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
<?php
/**
make an http POST request and return the response content and headers
@param string $url url of the requested script
@param array $data hash array of request variables
@return returns a hash array with response content and headers in the following form:
array ('content'=>'<html></html>'
, 'headers'=>array ('HTTP/1.1 200 OK', 'Connection: close', ...)
)
*/
function http_post ($url, $data)
{
$data_url = http_build_query ($data);
$data_len = strlen ($data_url);
return array (
'content'=>file_get_contents ($url, false, stream_context_create (array ('http'=>array ('method'=>'POST'
, 'header'=>"Connection: closernContent-Length: $data_lenrn"
, 'content'=>$data_url
))))
, 'headers'=>$http_response_header
);
}
?>
francois hill
8 years ago
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.
Drat.
fibrefox at dynamicfiles dot de
4 years ago
If you want to insert tracking-scripts into your shopping-system, some scripts doesn't support intelligent detection of HTTPS, so i made a script i put on the server that rewrites 'http' to 'https' in the script, assuming everything has to be UTF-8 encoded (as a fallback it makes a redirect).
It is important that the HTTPS-source DOES exist!
<?php
function file_get_contents_utf8($fn) {
$opts = array(
'http' => array(
'method'=>"GET",
'header'=>"Content-Type: text/html; charset=utf-8"
)
);
$context = stream_context_create($opts);
$result = @file_get_contents($fn,false,$context);
return $result;
}
header("Content-Type: text/html; charset=utf-8");
$tPath = "URL YOU WANT TO MODIFY";
$result = file_get_contents_utf8("http://".$tPath);
if(
$result == false){
header("Location: https://".$tPath); // fallback
exit();
}
else{
echo mb_ereg_replace("http","https",$result);
}
?>
KrisWebDev
5 years ago
If your file_get_contents freezes during several seconds, here is maybe your answer:
Beware that the default keepalive timeout of Apache 2.0 httpd is 15 seconds. This is true for HTTP/1.1 connections, which is not the default behavior of file_get_contents but you can force it, especially if you are trying to act as a web browser. I don't know if this is also the case for HTTP/1.0 connections.
Forcing the server to close the connection would make you gain those 15 seconds in your script:
<?php
$context = stream_context_create(array('http' => array('header'=>'Connection: close')));
$content = file_get_contents("http://www.example.com/test.html");
?>
Another way of resolving slowness issues is to use cURL or fsockopen. Bear in mind that contrary to the behavior of web browsers, file_get_contents doesn't return the result when the web page is fully downloaded (i.e. HTTP payload length = value of the response HTTP "Content-Length" header) but when the TCP connection is closed.
I hope this behavior will change in future releases of PHP.
This has been experienced with PHP 5.3.3.
bearachute at gmail dot com
8 years ago
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!
siegfri3d at gmail dot com
9 years ago
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:
<?php
$content=file_get_contents("http://www.google.com",FALSE,NULL,0,20);
echo $content;
?>
This will echo the 20 first bytes of the google.com source code.
slymak at gmail dot com
5 years ago
If working file is bigger than 64kb and you getting deadlock. Your buffer is overflow. Here are two way how to avoid that.
1) use temporary file for descriptor
<?php
$descriptorspec = array(
0 => array("file", "/tmp/ens/a.ens","r"), // stdin is a pipe that the child will read from
1 => array("file", "/tmp/ens/a.html","w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/ens/error-output.txt", "a") // stderr is a file to write to
);
?>
2) inline read using stream_set_blocking. PHP doesn't proper handle last part of file.
<?php
$READ_LEN = 64*1024;
$MAX_BUF_LEN = 2*$READ_LEN;
$url = "http://some.domain.com:5984/".$db."/".$member."/contents";
$src = fopen($url,"r");
$cwd = '/tmp';
$cmd['enscript'] = "/usr/bin/enscript";
$cmd['enscript-options'] = " -q --language=html --color -Ejcl -o -";
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w") // stdout is a pipe that the child will write to
);
$ph=proc_open($cmd['enscript']." ".$cmd['enscript-options'],$descriptorspec,$pipes,$cwd);
stream_set_blocking($src,0);
stream_set_blocking($pipes[0],0);
stream_set_blocking($pipes[1],0);
$CMD_OUT_OPEN = TRUE; $k = 0;
while (!feof($pipes[1]) || !feof($src) || $k > 0) {
if (!feof($src) && $k+$READ_LEN <= $MAX_BUF_LEN) {
$input .= fread($src,$READ_LEN);
$k = strlen($input);
}
if ($k > 0) {
$l = fwrite($pipes[0],$input);
$k -= $l;
$input = substr($input,$l);
}
if ($CMD_OUT_OPEN && $k == 0 && feof($src)) {
fclose($pipes[0]);
$CMD_OUT_OPEN = FALSE;
}
$output = fread($pipes[1],$READ_LEN);
$outputn = str_replace("<H1>(stdin)</H1>","",$output);
echo $outputn;
}
fclose($pipes[1]);
$return_value = proc_close($ph);
?>
werdnanoslen at gmail dot com
3 years ago
This is an easy way to trigger scripts by listening for POSTs. I simply point a service's webhook url to the script, which file_get_contents("php://input"), cast to an array, and then simplexml_load_string() to parse it and use one of the keys' data as the parameter for my script.
Yoga Wibowo Aji
5 years ago
read text per line and convert to array
for example, the input file is input.txt
the input file containt text below
one
two
three
four
five
++++++++++++++++++++++++++
read value per line
<?php
$data = file_get_contents("input.txt"); //read the file
$convert = explode("n", $data); //create array separate by new linefor ($i=0;$i<count($convert);$i++)
{
echo $convert[$i].', '; //write value by index
}
?>
++++++++++++++++++++++++++
Output :
one, two, three, four, five,
andrew at 21cv dot co dot uk
3 years ago
Negative offsets don't work as you might expect (like in http://php.net/substr for example)
So
<?php echo file_get_contents(__FILE__, false, null, -10) ?>
does the same as
<?php echo file_get_contents(__FILE__, false, null, 0) ?>
To get the last 10 characters of a file, you need to use
<?php echo file_get_contents (__FILE__, false, null, (filesize (__FILE__) - 10)) ?>
Greg Ambrose (greg at catalina-it dot com dot au)
9 years ago
[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.
godwraith01 at yahoo dot com
4 years ago
I experienced a problem in using hostnames instead straight IP with some server destinations.
If i use file_get_contents("www.jbossServer.example/app1",...)
i will get an 'Invalid hostname' from the server i'm calling.
This is because file_get_contents probably will rewrite your request after getting the IP, obtaining the same thing as :
file_get_contents("xxx.yyy.www.zzz/app1",...)
And you know that many servers will deny you access if you go through IP addressing in the request.
With cURL this problem doesn't exists. It resolves the hostname leaving the request as you set it, so the server is not rude in response.
forestrf at gmail dot com
2 years ago
It is important to write the method in capital letters like "GET" or "POST" and not "get" or "post". Some servers can respond a 400 error if you do not use caps in the method.
php [spat] hm2k.org
8 years ago
I decided to make a similar function to this, called file_post_contents, it uses POST instead of GET to call, kinda handy...
<?php
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; }
}
$url['query']=isset($url['query'])?$url['query']:'';$url['protocol']=$url['scheme'].'://';
$eol="rn";$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.
$eol.$url['query'];
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
if($fp) {
fputs($fp, $headers);
$result = '';
while(!feof($fp)) { $result .= fgets($fp, 128); }
fclose($fp);
if (!$headers) {
//removes headers
$pattern="/^.*rnrn/s";
$result=preg_replace($pattern,'',$result);
}
return $result;
}
}
?>
Anonymous
5 years ago
The offset is 0 based. Setting it to 1 will skip the first character of the stream.
richard dot quadling at bandvulc dot co dot uk
10 years ago
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!!!
3n1gm4 [at] gmail [dot] com
8 years ago
This is a nice and simple substitute to get_file_contents() using curl, it returns FALSE if $contents is empty.
<?php
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);
curl_close($c);
if (
$contents) return $contents;
else return FALSE;
}
?>
Hope this help, if there is something wrong or something you don't understand let me know :)
ken at wetken dot net
6 years ago
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.
pperegrina
4 years ago
For those having this problem when trying to get_file_contents(url):
Warning: file_get_contents(url): failed to open stream: HTTP request failed! in xx on line yy
If you are behind a SonicWall firewall, read this:
https://bugs.php.net/bug.php?id=40197
(this little line: uncheck a box in the internal settings of the firewall labled "Enforce Host Tag Search with for CFS")
Apparently by default SonicWall blocks any HTTP request without a "Host:" header, which is the case in the PHP get_file_contents(url) implementation.
This is why, if you try to get the same URL from the same machine with cURL our wget, it works.
I hope this will be useful to someone, it took me hours to find out :)
vlad dot wing at gmail dot com
6 years ago
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.
<?php
$result=file_get_contents("http://www.example.com");
if ($result === false)
{
// treat error
} else {
// handle good case
}
?>
[EDIT BY thiago: Has enhacements from an anonymous user]
rutger at webjin dot nl
6 years ago
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.
dustin at dumontproject dot com-spam sux
4 years ago
For those who use file_get_contents for JSON or other RESTful services - like my architecture did for a big site - this will probably help a lot.
We struggled with having the site using get urls that would go through our load balancer instead of hitting the local server.
What we did was load this function through a local url and set the Host: header for our virtualhost entries on the site we wanted to laod.
This code solved our issue:
<?php//set the header context stream for virtualhost lookup
$context = stream_context_create(array('http' => array('header' => 'Host: www.VIRTUALHOSTDOMAIN.com')));//use a localhost url or alternatively 127.0.0.1 ip
$url = 'http://localhost/rest-service/?get-user&id=######';//fetch the data through webserver using the Host http header we set
$data = json_decode(file_get_contents($url, 0, $context));//verify you have your data
var_dump($data);?>
contact at webapp dot fr
5 years ago
When using a URI with a login / password (HTTP or FTP, for an example), you may need to urlencode the password if it contains special characters.
Do not urlencode the whole URI, just the password.
Don't do :
urlencode('ftp://login:mdp%?special@host/dir/file')
Do :
'ftp://login:' . urlencode('mdp%?special') . '@host/dir/file';
Might seem obvious, but is worth noting.
luby dot pl at gmail dot com
2 years ago
The funniest thing there is that seeking on non local files may, or may not work. This is unpredictable, and thus should throw rather than doing some magical stuff.
Also trying to read non local file which doesn't exists results in FALSE returned and no single warning emitted.
EOD
7 years ago
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.
corey at effim dot com
6 years ago
In my dev environment with a relatively low-speed drive (standard SATA 7200RPM) reading a 25MB zip file in 10 times...
<?php
$data
= `cat /tmp/test.zip`;
// 1.05 seconds
$fh = fopen('/tmp/test.zip', 'r');
$data = fread($fh, filesize('/tmp/test.zip'));
fclose($fh);
// 1.31 seconds
$data = file_get_contents('/tmp/test.zip');
// 1.33 seconds
?>
However, on a 21k text file running 100 iterations...
<?php
$data
= `cat /tmp/test.txt`;
// 1.98 seconds
$fh = fopen('/tmp/test.txt', 'r');
$data = fread($fh, filesize('/tmp/test.txt'));
fclose($fh);
// 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.
srgold at hotmail dot com
1 year ago
Be sure to remove newlines from variables when using file_get_contents, or you'll receive the following error:
file_get_contents(): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
leomac at inbox dot ru
3 years ago
Reading all script input is simple task with file_get_contents, but it depends on what SAPI is being used.
Only in Apache, not in CLI:
<?php
$input = file_get_contents("php://input");
?>
Only in CLI, not in Apache:
<?php
$input = file_get_contents("php://stdin");
?>
In Apache php://stdin will be empty, in CLI php://input will be empyt instead with no error indication.