🤯 60% OFF BLACK FRIDAY SALE 650+ books, courses & coding assessments!

Speed Up Your Website With PHP Buffer Flushing

    Craig Buckler

    PHP output buffering is normally enabled by default. In older versions of PHP, a string would be sent to your browser every time the interpreter encountered an echo statement or text outside the PHP delimiters.

    Output buffering makes this process quicker and more efficient. The buffer is essentially a big memory-resident string. When text is output, it’s appended to the buffer rather than returned to the browser immediately. The buffer is then “flushed”, i.e. its contents are transmitted and the string is reset pending further output. Flushing occurs when:

    1. the PHP interpreter reaches the end of the page
    2. the buffer exceeds the number of bytes specified within PHP’s output_buffering configuration setting, or
    3. the flush() or ob_flush() functions are called.

    There are a few caveats but, assuming it works within your environment, you should consider flushing the buffer immediately after the page’s </head> tag, e.g.

    <!DOCTYPE html>
    <html lang="en">
    <meta charset="UTF-8" />
    <title>Buffer flushing in action</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <link rel="shortcut icon" href="favicon.ico" />
    // flush the buffer

    (If you’re using WordPress, you could use similar code in your theme’s header.php file.)

    Once the browser has received the HTML head, it can begin to download all linked CSS files, favicons and other resources. These downloads can occur while the browser is idle and waiting for the main body content.

    The speed increase will depend on the server-side processing required, the weight of your page, the quantity and size of your CSS files, and whether the browser has cached any resources. However, it’s such a simple optimization, there’s little reason not to do it.

    I’d be interested to know whether this technique results in a perceivable speed difference on your website or application.