- file_get_contents
- Список параметров
- Возвращаемые значения
- Ошибки
- Список изменений
- Примеры
- Примечания
- Смотрите также
- ob_get_length
- Примеры
- Смотрите также
- User Contributed Notes 5 notes
- PHP: Get the size of a remote file.
- Using cURL to get the size of a remote file.
- Using PHP’s get_headers function to get the size of a remote file.
file_get_contents
Данная функция похожа на функцию file() с той лишь разницей, что file_get_contents() возвращает содержимое файла в строке, начиная с указанного смещения offset и до length байт. В случае неудачи, file_get_contents() вернёт false .
Использование функции file_get_contents() наиболее предпочтительно в случае необходимости получить содержимое файла целиком, поскольку для улучшения производительности функция использует технику отображения файла в память (memory mapping), если она поддерживается вашей операционной системой.
Замечание:
Если вы открываете URI, содержащий спецсимволы, такие как пробел, вам нужно закодировать URI при помощи urlencode() .
Список параметров
Замечание:
Можно использовать константу FILE_USE_INCLUDE_PATH для поиска файла в include path. Только помните, что если вы используете строгую типизацию, то так сделать не получится, поскольку FILE_USE_INCLUDE_PATH имеет тип int . В таком случае используйте true .
Корректный ресурс контекста, созданный с помощью функции stream_context_create() . Если в использовании особого контекста нет необходимости, можно пропустить этот параметр передав в него значение null .
Смещение, с которого начнётся чтение оригинального потока. Отрицательное значение смещения будет отсчитываться с конца потока.
Поиск смещения ( offset ) не поддерживается при работе с удалёнными файлами. Попытка поиска смещения на нелокальных файлах может работать при небольших смещениях, но результат будет непредсказуемым, так как функция работает на буферизованном потоке.
Максимальный размер читаемых данных. По умолчанию чтение осуществляется пока не будет достигнут конец файла. Учтите, что этот параметр применяется и к потоку с фильтрами.
Возвращаемые значения
Функция возвращает прочтённые данные или 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 Получить и вывести исходный код домашней страницы сайта
Пример #2 Поиск файлов в include_path
// Если включены строгие типы, то есть объявлено (strict_types=1);
$file = file_get_contents ( ‘./people.txt’ , true );
// Иначе
$file = file_get_contents ( ‘./people.txt’ , FILE_USE_INCLUDE_PATH );
?>?php
Пример #3 Чтение секции файла
// Читаем 14 символов, начиная с 21 символа
$section = file_get_contents ( ‘./people.txt’ , FALSE , NULL , 20 , 14 );
var_dump ( $section );
?>?php
Результатом выполнения данного примера будет что-то подобное:
Пример #4 Использование потоковых контекстов
// Создаём поток
$opts = array(
‘http’ =>array(
‘method’ => «GET» ,
‘header’ => «Accept-language: en\r\n» .
«Cookie: foo=bar\r\n»
)
);
?php
$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
ob_get_length
Возвращает размер в байтах содержимого буфера вывода или false , если буферизация не активна.
Примеры
Пример #1 Простой пример использования функции ob_get_length()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 5 notes
I use this function to produce a small speed test in my pages since I run my website from my home computers.
ob_start ();
$StartTime = microtime ( 1 );
?>
.. webpage data goes here ..
// footer?
printf ( «%s seconds to produce (%skb/sec)» ,
microtime ( 1 )- $StartTime ,
Round (( ob_get_length ()/( microtime ( 1 )- $StartTime ))/ 1024 ));
ob_end_flush ();
?>
Note: don’t forget the «speed» depends on how quick the content is actually generated and not on the speed the data is sent to the client..
However it would be good to see such function to get the real speed. 🙂
There is a work-around for the situation you need to get length of the gz-ed buffer.
ob_end_flush(); // The ob_gzhandler one
ob_end_flush(); // The main one
If you don’t buffer your output, it doesn’t seem like it would be possible for a web server to output a Content-Length header. For static files it can check the filesize, but for dynamic files that send output a little by little there is no way to know how many bytes it is going to output. And the headers have to be sent before a single byte is output.
Also if you’re wondering why the Content-Length is important, the browser doesn’t close the connection as long as the script is running. So if you register time consuming shutdown functions, the browser will still ‘spin’ waiting for more content until they complete. (I’m not sure this happens under all conditions, but I am certain the sending the Content-Length always prevents this.)
You might take note that this manual page does not currently output any Content-Length header.
Alternatively using mb_strlen($output, ‘latin1’) seems to work to determine bytes in a string. strlen may or may not depending on if it has been set up as a multibyte or not.
> Dude, your web server will compute Content-length for you!
I’ve noticed that Apache 1.3 doesn’t do that.
However, if you’re running Apache 2.2 (and maybe 2.0, haven’t experienced that yet) you don’t need to worry about Content-Length.
Here is an easy way to get the header Content-Lenght.
ob_start();
?>
$size=ob_get_length();
header(«Content-Length: $size»);
ob_end_flush();
?>
- Функции контроля вывода
- flush
- ob_clean
- ob_end_clean
- ob_end_flush
- ob_flush
- ob_get_clean
- ob_get_contents
- ob_get_flush
- ob_get_length
- ob_get_level
- ob_get_status
- ob_gzhandler
- ob_implicit_flush
- ob_list_handlers
- ob_start
- output_add_rewrite_var
- output_reset_rewrite_vars
PHP: Get the size of a remote file.
In this article, we will show you how to get the size of a remote file using PHP.
We will also include both a cURL and a non-cURL example.
Both of these solutions will attempt to get the size of the file without actually downloading it.
Be warned that there is no surefire way to get the size of a remote file without downloading it. This method relies on the server in question returning a Content-Length header in the header response. Content-Length is an optional header for servers, which means that it might not always be present.
Using cURL to get the size of a remote file.
If you would like to use PHP’s cURL extension to get the size of a remote file, then you can use the following example:
//URL of the remote file that you want to get //the file size of. $remoteFile = 'http://site.com/file.mp4'; //Create a cURL handle with the URL of //the remote file. $curl = curl_init($remoteFile); //Set CURLOPT_FOLLOWLOCATION to TRUE so that our //cURL request follows any redirects. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //We want curl_exec to return the output as a string. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //Set CURLOPT_HEADER to TRUE so that cURL returns //the header information. curl_setopt($curl, CURLOPT_HEADER, true); //Set CURLOPT_NOBODY to TRUE to send a HEAD request. //This stops cURL from downloading the entire body //of the content. curl_setopt($curl, CURLOPT_NOBODY, true); //Execute the request. curl_exec($curl); //Retrieve the size of the remote file in bytes. $fileSize = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD); var_dump($fileSize); //Convert it into KB $fileSizeKB = round($fileSize / 1024); echo 'File is ' . $fileSizeKB . ' KB in size.';
In the code above, we configured cURL to send a HEAD request to the remote file in question.
We then extracted the “Content-Length” header by using the curl_getinfo function and the CURLINFO_CONTENT_LENGTH_DOWNLOAD option.
Note that if the Content-Length header is not returned by the remote server, curl_getinfo will return a -1 (minus one).
You should also note that this is not a reliable way to check if a remote file exists. This is because curl_getinfo might return -1 even if the resource in question exists.
If you want to check if a remote file actually exists or not, then you should read our guide on checking to see if an HTTP resource exists.
Using PHP’s get_headers function to get the size of a remote file.
If you do not have cURL installed, then you can use PHP’s inbuilt get_headers function:
//URL of the remote file that you want to get //the file size of. $remoteFile = 'http://remote-site.com/video.mp4'; //Get the header response for the file in question. $headers = get_headers($remoteFile, 1); //Convert the array keys to lower case for the sake //of consistency. $headers = array_change_key_case($headers); //Set to -1 by default. $fileSize = -1; //Check to see if the content-length key actually exists in //the array before attempting to access it. if(isset($headers['content-length'])) < $fileSize = $headers['content-length']; >var_dump($fileSize);
- We fetched the response headers for the resource in question by using PHP’s get_headers function. We passed in 1 as the second parameter. The second parameter tells get_headers to parse the response and set each header as an array key.
- To keep things consistent, we converted all array keys to lower case by using the array_change_key_case function.
- We set the $fileSize variable to -1 by default. If the $fileSize variable is still -1, we will know that the Content-Length header was not returned by the server.
- We check to see if the “content-length” key exists in our $headers array. Failing to use isset in this particular scenario could result in an undefined index warning. As stated above, the Content-Length header is optional.
- Finally, we printed the size of the remote file in bytes.
If you are wanting to get the size of a local file, then you should check out our tutorial on how to get a file’s size in PHP.