makeee
makeee

Reputation: 2815

Save gzipped html file with PHP that is readable by browsers

I'm caching the main page of my site as a flat html file, and then with .htaccess loading that file if the user is not logged in (since no user specific info is displayed), instead of loading my entire php framework.

The one downside to this is that PHP doesn't gzip the file automatically, since PHP is not even being used, as it's just a plain html file that is being loaded by the browser.

I tried this:

$html = gzencode($html);
$fp = fopen($cachefile, 'w'); 
fwrite($fp, $html); 

But when the file url is loaded in a browser it is just a bunch of weird characters.

EDIT: I guess one simple solution would be to save the files as .php instead of html, that way the php ob_gzhandler compresses the file. I'm wondering if there's a performance gain to be had by serving up html that is already gzipped and skipping php altogether..

Upvotes: 0

Views: 917

Answers (1)

Trott
Trott

Reputation: 70163

UPDATE: As OP discovered, ob_gzhandler() can deal with this sort of use case, and is not a bad way to go.

ORIGINAL ANSWER: It is likely that, even if you manage to make this work somehow, it will result in poorer performance than simply having the file as a plain text file on your file system.

If you want to take advantage of gzip compression, have Apache do it with mod_deflate. Store your file uncompressed. Apache will deal with the compression issue.

But before you go through any trouble getting that set up: How big can this file be? If it is not a very large HTML file, the cost of the overhead of having to uncompress the file every transaction probably outweighs the benefit of the actual compression. You'd really only see a benefit with very large HTML files, and those files would probably cause the browser to come to a screeching halt anyway.

All that said, you can use gzdecode() to uncompress the file, but then you're not serving up the static file--you're running it through PHP before serving it. Again, for this use case, you're best bet is probably to just serve up the straight HTML rather than messing with compression.

Upvotes: 1

Related Questions