Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient/faster when calling a cached image?

Tags:

php

gd

i made an image resizer in php. When an image is resized, it caches a new jpg file with the new dimensions. Next time you call the exact img.php?file=hello.jpg&size=400 it checks if the new jpg has already been created.

  1. If it has NOT been created yet, it creates the file and then prints the output (cool).
  2. If it ALREADY exists, no new file needs to be generated and instead, it just calls the already cached file.

My question is regarding the second scenario. Which of these is faster?

  1. redirecting: header('Location: cache/hello_400.jpg');die();
  2. grabbing data and printing the cached file: $data = file_get_contents('cache/hello_400.jpg'); header('Content-type: '.$mime); header('Content-Length: '.strlen($data)); echo $data;

Any other ways to improve this?

If someone wants the generated code, check this out: http://egobits.com/misc/img.phps

Thanks to all for the help!

like image 544
Andres SK Avatar asked May 13 '10 15:05

Andres SK


1 Answers

I would opt for never printing the data to the browser. Both scenarios should throw a permanent redirect to the generated image. Except if the image doesn't exist yet, it is created before the Location header is sent.

Edit:

Just to be clear about what I mean by permanent redirect...

header('HTTP/1.1 301 Moved Permanently'); 
header('Location: http://path/to/image'); 
like image 126
Matt Avatar answered Nov 12 '22 17:11

Matt