Skip to content

Send a Content-Length header from PHP

When a static file is requested from an app on your server, a Content-Length HTTP response header is automatically included in the response sent to the browser.

However, for dynamic content such as HTTP responses from PHP scripts, the Content-Length header must be set by the code generating the response. Additionally, steps must be taken to ensure the header is not removed by Nginx or Apache.

Use PHP output buffering

To send Content-Length headers from your PHP scripts, enable output buffering in your PHP code and use the length of the buffered output as the value of the Content-Length header.

To set a Content-Length header without using compression:

<?php
// without compression
ob_start();
echo "this is the page content";
header('Content-Length: '.ob_get_length());
ob_end_flush();

To set a Content-Length header and have the content compressed with gzip:

<?php
// with compression
ob_start();
ob_start('ob_gzhandler');
echo "this is the page content";
ob_end_flush(); // flush the ob_gzhandler output buffer
header('Content-Length: '.ob_get_length()); // the length of the gzip'd content
ob_end_flush();

Configure Apache to allow Content-Length headers from PHP

Add the following to the app’s .htaccess file so Apache will allow PHP scripts to provide Content-Length response headers.

SetEnv ap_trust_cgilike_cl

Disable compression in Nginx if PHP output is uncompressed

If you did not use compression when you enabled output buffering in PHP, Nginx will compress the response before sending the response to the browser. When the response is compressed by Nginx, the Content-Length header will be removed.

To configure Nginx so that uncompressed responses from PHP will not be automatically compressed, create a custom Nginx configuration file for the app:

/etc/nginx-sp/vhosts.d/APPNAME.d/disable_compression.conf

with the contents:

gzip off;
brotli off;

and then restart Nginx with:

Terminal window
sudo service nginx-sp restart

Learn more about customizing Nginx.