I have this short external php script (named resize.php) which I am calling to from other php scripts when I want to resize/thumbnail images. I would like to change the script to work as an internal function instead of an external php script and I don't know how to convert it to a function that will do the job.
This is how it is being called:
<img src="resize.php?image=images/IMG228.jpg&width=165" border="0" alt="foo" width="165" height="165" title="">
The main reason I want to change it to be a function is because due to caching issues, when it is an external php script, if it has already been called/loaded by the browser, it doesn't load it again, even if the image on the server (to be resized) is newer, and despite the fact that the resizer.php itself had a caching detection and refresh implemented. If it is an internal resizer function, I assume this issue will be resolved.
This is the resizer.php script:
<?php
if (isset($_GET['image']) && isset($_GET['width']) && is_numeric($_GET['width'])) {
// Get image name
$original_image = $_GET['image'];
// Watermarks
$wmark = 'watermark.png'; //largest watermark
$wmarkm = 'watermark_m.png'; //medium watermark
$wmarks = 'watermark_s.png'; //smallest watermark
$wmarkno = 'nowatermark.png'; //No watermark
// Maximum image width
$max_width = (int) $_GET['width'];
// Maximum image height
$max_height = "800";
if (file_exists($original_image)) {
$cached = 'cache/' . preg_replace('/(\.\w+$)/', ".{$max_width}\\1", $original_image);
if (file_exists($cached)) {
$cst = stat($cached);
$fst = stat($original_image);
if ($fst[9] <= $cst[9] && $fst[10] <= $cst[10]) {
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $cst[9]) {
// header("HTTP/1.0 304 Not Modified");
header("HTTP/1.1 304 Not Modified");
// header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($cached)).' GMT', true, 304);
} else {
header('Content-type: image/jpeg');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $cst[9]) . ' GMT');
header('Cache-Control: private');
// print file_get_contents($cached);
readfile("{$cached}");
}
exit;
}
}
if ($max_width > 300) {
$watermark = $wmark;
} elseif ($max_width > 152 && $max_width < 300) {
$watermark = $wmarkm;
} elseif ($max_width > 50 && $max_width < 151) {
$watermark = $wmarks;
} else {
$watermark = $wmarkno;
}
//create the resized image
exec("gm convert -filter Lanczos {$original_image} -thumbnail {$max_width}x{$max_height} -quality 90 -unsharp 2x0.5+0.7+0 {$cached}");
//apply the watermark and recreate the watermarked image, overwriting the previously resized image
exec("gm composite -quality 90 -dissolve 100 -gravity center {$watermark} {$cached} {$cached}");
header('Content-type: image/jpeg');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: private');
readfile("{$cached}");
}
}
?>