This gzipContent function will provide you the ability to reduce the size of your response by gzipping the content if the client supports it. It will also handle sending the response by default, but options exist to return the content instead if further processing is required.

Alternatively besides using this function you could write the line ob_start("ob_gzhandler"); before you start outputting any content and then followup with ob_end_flush(); when you are done outputting content and that would automatically handle gzipping the content for you. Compared to the alternate method, this gzip function allows you to be more explicate and provides you more control on handling the gzipped content.

/**
 * Gzip Content
 *
 * This function will check if a client supports gzipped content and if so it will return the content gzipped.
 *
 * @param string $content The content to be gzipped.
 * @param bool $checkClient By default it will only gzip content if the client indicates support for gzip.
 * @param bool $return By default the function sends the response with the Content-Encoding header set to indicate its gzipped.
 * @return string
 */
function gzipContent($content, $checkClient = true, $return = false): string
{
    $enabled = ! $checkClient || strpos($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '', 'gzip') !== false;

    if ($enabled) {
        $content = gzencode(trim(preg_replace('/\s+/', ' ', $content)), 9);

        if (! $return) {
            header('Content-Encoding: gzip');
        }
    }

    if ($return) {
        return $content;
    }

    echo $content;
    exit();
}

This code snippet was published on It was last edited on

0

0 Comments

  • Votes
  • Oldest
  • Latest