Php file get contents ошибки

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contentsЧитает содержимое файла в строку

Описание

file_get_contents(
    string $filename,
    bool $use_include_path = false,
    ?resource $context = null,
    int $offset = 0,
    ?int $length = null
): string|false

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

Замечание:

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

Список параметров

filename

Имя читаемого файла.

use_include_path

Замечание:

Можно использовать константу
FILE_USE_INCLUDE_PATH для поиска файла
в include path.
Только помните, что если вы используете строгую типизацию,
то так сделать не получится, поскольку
FILE_USE_INCLUDE_PATH имеет тип int.
В таком случае используйте true.

context

Корректный ресурс контекста, созданный с помощью функции
stream_context_create(). Если в использовании
особого контекста нет необходимости, можно пропустить этот параметр
передав в него значение null.

offset

Смещение, с которого начнётся чтение оригинального потока.
Отрицательное значение смещения будет отсчитываться с конца потока.

Поиск смещения (offset) не поддерживается при
работе с удалёнными файлами. Попытка поиска смещения на нелокальных
файлах может работать при небольших смещениях, но результат будет
непредсказуемым, так как функция работает на буферизованном потоке.

length

Максимальный размер читаемых данных. По умолчанию чтение
осуществляется пока не будет достигнут конец файла. Учтите, что
этот параметр применяется и к потоку с фильтрами.

Возвращаемые значения

Функция возвращает прочтённые данные или false в случае возникновения ошибки.

Внимание

Эта функция может возвращать как логическое значение false, так и значение не типа boolean, которое приводится к false. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Ошибки

Будет сгенерирована ошибка уровня E_WARNING в случаях,
если не удастся найти filename, задан length
меньше нуля, или поиск по смещению offset в потоке
завершится неудачно.

Когда file_get_contents() вызывается в каталоге,
в Windows ошибка генерируется E_WARNING,
а с PHP 7.4 также в других операционных системах.

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

Версия Описание
8.0.0 Параметр length теперь допускает значение null.
7.1.0 Добавлена поддержка отрицательных значений offset.

Примеры

Пример #1 Получить и вывести исходный код домашней страницы сайта


<?php
$homepage
= file_get_contents('http://www.example.com/');
echo
$homepage;
?>

Пример #2 Поиск файлов в include_path


<?php
// Если включены строгие типы, то есть объявлено (strict_types=1);
$file = file_get_contents('./people.txt', true);
// Иначе
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Пример #3 Чтение секции файла


<?php
// Читаем 14 символов, начиная с 21 символа
$section = file_get_contents('./people.txt', FALSE, 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);
?>

Примечания

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

Подсказка

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

Внимание

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

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

  • file() — Читает содержимое файла и помещает его в массив
  • fgets() — Читает строку из файла
  • fread() — Бинарно-безопасное чтение файла
  • readfile() — Выводит файл
  • file_put_contents() — Пишет данные в файл
  • stream_get_contents() — Читает оставшуюся часть потока в строку
  • stream_context_create() — Создаёт контекст потока
  • $http_response_header

Bart Friederichs

11 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);
?>


daniel at dangarbri dot tech

2 months ago


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.

soger

8 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 was resolve all problem, it’s work all links

public function getTitle($url)
    {
        try {
            if (strpos($url, 'www.youtube.com/watch') !== false) {
                $apikey = 'AIzaSyCPeA3MlMPeT1CU18NHfJawWAx18VoowOY';
                $videoId = explode('&', explode("=", $url)[1])[0];
                $url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $videoId . '&key=' . $apikey . '&part=snippet';

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_VERBOSE, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
                curl_close($ch);

                $data = json_decode($response);
                $value = json_decode(json_encode($data), true);

                $title = $value['items'][0]['snippet']['title'];
            } else {
                set_error_handler(
                    function () {
                            return false;
                    }
                );
                if (($str = file_get_contents($url)) === false) {
                    $title = $url;
                } else {
                    preg_match("/<title>(.*)</title>/i", $str, $title);
                    $title = $title[1];
                    if (preg_replace('/[x00-x1Fx7F-xFF]/', '', $title))
                        $title = utf8_encode($title);
                    $title = html_entity_decode($title);
                }
                restore_error_handler();
            }
        } catch (Exception $e) {
            $title = $url;
        }
        return $title;
    }

Если file_get_contents при загрузки файла из сети получает не 200-ый ответ, он выдает ошибку. Как эту ошибку перехватить? Использовать try / catch? Или просто проверить переменную, куда file_get_contents должен был записать ответ? Хочу сделать обработку ситуаций, когда целевой файл не существует или недоступен по каким-то причинам.

Нужно мне сделать функцию работающую по принципу чёрной коробки — функция принимает ссылку и возвращает скачанный файл, ну или false если скачать файл по какой-то причине не получилось (код ответа не 200, домен не существует, кривой SSL сертификат и так далее).

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
 

Last Updated :
07 May, 2021

Like Article

Save Article

Понравилась статья? Поделить с друзьями:
  • Php can not start ошибка
  • Php access denied for user ошибка
  • Photoshop произошла ошибка при открытии принтера
  • Photoshop ошибка при открытии файла
  • Photoshop обнаружил ошибку с драйвером дисплея