Jump to content

Writing images to file with headers


Jenosavel

Recommended Posts

I have a dynamically generated image which I need to write to file to call later.  My problem is that I need this image to have appropriate expiration headers included in it, and these headers vary individually file-by-file making .htaccess controls not an option.

 

I can write expiration headers if I'm outputting the image directly to the browser with this:

header("Content-Type: image/jpeg");
header('Expires: "' . gmdate("D, d M Y H:i:s", $expirationDate) . '"');
imagepng($image, NULL);

 

Or I can write the image to a file to be used later with this:

imagepng($image, $filepath)

 

But I can't for the life of me figure out how to combine those two and write the image to a file while including its expiration headers.  Anyone know what I need to be doing?

Link to comment
https://forums.phpfreaks.com/topic/198602-writing-images-to-file-with-headers/
Share on other sites

Any ideas?  Since

header("Content-Type: image/jpeg");
header('Expires: "' . gmdate("D, d M Y H:i:s", $expirationDate) . '"');
imagepng($image, NULL);

works, I've tried writing php files that would load as images as follows

fwrite($myFile, '<?php header("Content-Type: image/jpeg");
header(\'Expires: "' . gmdate("D, d M Y H:i:s", $growthDate) . '"\'); ?>');
ob_start();
imagepng($image);
imagedestroy($image);
fwrite($myFile, ob_get_flush());

This writes a bunch of corrupted nonsense, clearly no longer recognizing the image data as image data.  It's not a problem with using the output buffer to grab the image, as if I simply echo the result of ob_get_flush() at the end, the image displays there fine.  It just doesn't survive the file write.

I think I found my answer.  It requires handling 2 files instead of one.

//save cache of the image
imagepng($image, $filepath . '.png'); 
imagedestroy($image);

//write header expiring information
$myFile = fopen ($filepath . '.php', 'w');
fwrite($myFile, '<?php header("Content-Type: image/jpeg");
		header(\'Expires: "' . gmdate("D, d M Y H:i:s", $growthDate) . '"\');
		readfile("' . $filepath . '.png"); ?>');
fclose($myFile);

Then I point my pages to the php file and it will display as my properly caching png.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.