Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

PHP Serve Compressed Images

Recommended Posts

Posted · Original PosterOP

So I have a  PHP script that will serve users a photo based on a GET request. See spoiler for code:


$file = $_GET['i'];
$size = getimagesize($file);
$fp = fopen($file, "rb");
if ($size && $fp) {
    header("Content-type: {$size['mime']}");
} else {
	header("Content-type: image/png");
	header("HTTP/1.0 404 Not Found");



Is there some way to add a GET like ?i=myfile.png&c=1 where c=1 will tell the script to compress the image before serving it to the user?

Im using PGP 7.1.7 on IIS.

Link to post
Share on other sites

Compressing the image on upload will reduce a lot of server load.

But keep the original too,so you are able to show that too if you really want too.


Converting images to jpeg's will be already a good step.

Quote or mention me if not feel ignored 

Link to post
Share on other sites

Look into imagejpeg() as said previously you can compress them on upload or you can do it on serve but save/cache the compressed image for later use. The process would go like 



	$file = "files/photos/source/" . $_GET["file"];
	$compressdFile = "files/photos/compressed/" . $_GET["file"];
	/* do security check here to make sure the user can access this file */ 
	if (file_exists($compressdFile)) {
		/* serve $compressdFile */
	} else {
		/* compress file */
		/* save compressed file to $compressdFile */
 		/* serve $compressdFile */



Or you can always compress on upload and still use this way to support already uploaded images

Link to post
Share on other sites
3 hours ago, MyName13 said:

Is there a reason why you can't compress the images before they are needed?

You can but it adds an overhead on the CPU so as the site/application scales there will be more strain on the server. In the long run, it's cheaper to upgrade your storage rather than the CPU.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now