Search code examples
phphttp-headerstwigcontent-length

How to return Content-Length header for TWIG rendered page?


I am rendering a TWIG template to generate a CSV file to download. In order to show a progress bar for the download, the server must return the Content-Length header.

I tried rendering the TWIG template into a variable, calculating the length of this string, then outputting the content-length header immediately before echo'ing the rendered template:

$output = $twig->render(...);
header('Content-Length', strlen($output));
echo $output;

But this throws a server 500 error with the message "malformed header from script 'index.php': Bad header: Content-Length".

Am I missing something here? Seems this should be trivial.


Solution

  • The first parameter passed to header() should be the complete header string. I guess you expected header function to accept the first and second parameters like header(field name,field value), but that's not the case. You should headers as a single string like this:

    // something like 'Content length: 1234'
    header('Content-Length: ' . strlen($output));