← ServerPilot Docs

How to Send Content-Length Response Headers 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.

Sending Content-Length headers from PHP

Follow the steps below to send Content-Length headers from your PHP scripts.

Step 1: Use output buffering in your PHP code to set 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();

Step 2: Update the app's .htaccess file to allow Content-Length headers from PHP

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

SetEnv ap_trust_cgilike_cl

Step 3: If output from PHP is uncompressed, disable compression in Nginx

If you did not use compression in Step 1 above, 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 customize 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:

sudo service nginx-sp restart
Last updated: April 29, 2024

Launch your first site in 5 minutes