php - 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.




The first parameter passed toheader() should be the complete header string. I guess you expected header function to accept the first and second parameters likeheader(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));

People are also looking for solutions to the problem: LOAD DATA INFILE PHP/MySQL


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.