Php content length как вычислить

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.

Читайте также:  Background subtraction in opencv python

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

    Источник

    Правильная выдача заголовка Content-Length

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

     ob_start('ob_gzhandler'); 
    ob_implicit_flush(0); // отключаем неявную отправку буфера
    /* Здесь идет код скрипта, в нем не должно быть ob_flush, так как потом нельзя будет выдавать заголовки */
    if (!header_sent()) header('Content-Length: '.ob_get_length()); // если заголовки еще можно отправить, выдаем загловок Content-Length, иначе придется завершать передачу по закрытию

    ob_end_flush();
    exit(0);

    2 комментария:

    Нет

    Вообще, обычно chunked transfer применяется тогда, когда длина выдаваемой страницы целиком заранее не известна. В этом случае Content-Length лучше не выдавать вообще. А длина каждого отдельного chunk передается перед началом его самого, там все то же самое, только нет слов Content-Lenght и саму длину chunk нужно выдавать не через header, а обычным echo и переводить в hex.
    То есть получаем примерно такое:
    ob_start();
    header(‘Transfer-Encoding: chunked’);
    while (!$finish) // что-то делаем с выдачей с помощью echo
    echo sprintf(«%X\r\n»,ob_get_length()); // выдаем длину текущего chunk в hex
    ob_flush(); // выдаем сам chunk
    >
    echo «0\r\n»; // пустой chunk означает завершение передачи

    • © 2018—2023, 4X_Pro
    • Правила
    • Обо мне
    • Все проекты
    • Достижения

    Здесь можно задать мне вопрос или спросить совета по любой теме, затронутой в блогах или на форуме. После того, как я отвечу, вопрос и ответ появятся в соответствующем разделе. Но не забываем, что я — сторонник slow life, поэтому каких-либо сроков ответов не обещаю. Самые интересные вопросы станут основой для новых тем на форуме или записей в блоге.
    Сразу предупреждаю: глупости, провокации, троллинг и тому подобное летит прямо в /dev/null.

    Источник

    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);
    1. 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.
    2. To keep things consistent, we converted all array keys to lower case by using the array_change_key_case function.
    3. 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.
    4. 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.
    5. 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.

    Источник

    Получить размер POST-запроса в PHP

    Есть ли способ получить размер тела POST-запроса в PHP?

    Solutions Collecting From Web of «Получить размер POST-запроса в PHP»

    $size = (int) $_SERVER['CONTENT_LENGTH']; 

    Обратите внимание, что $ _SERVER [‘CONTENT_LENGTH’] устанавливается только в запросах HTTP через метод POST. Это необработанное значение заголовка Content-Length. См .: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13

    В случае загрузки файлов, если вы хотите получить общий размер загруженных файлов , вы должны перебирать элементы $ _FILE, чтобы суммировать каждый $ file [‘size’]. Точный общий размер не соответствует необработанному значению Content-Length из-за накладных расходов на кодирование данных POST.

    Также обратите внимание, что для ошибок файла вы должны проверить код $ file [‘error’] каждого элемента $ _FILES. Например, частичная загрузка вернет ошибку UPLOAD_ERR_PARTIAL, а пустые загрузки вернут UPLOAD_ERR_NO_FILE. См. Документацию по загрузке файлов в руководстве по PHP.

    Если вы пытаетесь выяснить, не удалось ли загрузить файл, вы должны использовать обработку ошибок PHP-файлов, как показано на приведенной ниже ссылке. Это самый надежный способ обнаружения ошибок при загрузке файлов:
    http://us3.php.net/manual/en/features.file-upload.errors.php

    Если вам нужен размер запроса POST без загрузки файлов , вы можете сделать это примерно так:

    $request = http_build_query($_POST); $size = strlen($request); 

    Я предполагаю, что он находится в $_SERVER[‘CONTENT_LENGTH’] .

    И если вам нужно это для обнаружения ошибок, загляните в $_FILES[‘filename’][‘error’] .

    $bytesInPostRequestBody = strlen(file_get_contents('php://input')); // This does not count the bytes of the request's headers on its body. 

    Я думаю, вы ищете $HTTP_RAW_POST_DATA

    Источник

Оцените статью