Skip to content

Instantly share code, notes, and snippets.

@oxyflour
Created September 25, 2015 13:02
Show Gist options
  • Save oxyflour/8eb67e5e760d532804c7 to your computer and use it in GitHub Desktop.
Save oxyflour/8eb67e5e760d532804c7 to your computer and use it in GitHub Desktop.
php script to cache images with memcache in Sina App Engine
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
// this is naive
function isValidUrl($url) {
return strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0;
}
// ref: http://stackoverflow.com/questions/28846006/php-create-thumbnail-image-from-url
function thumbnailJpeg($url, $width = 150, $height = true) {
$image = ImageCreateFromString(file_get_contents($url));
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
$output = ImageCreateTrueColor($width, $height);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
return $output;
}
function imageToString($image) {
ob_start();
ImageJpeg($image);
$content = ob_get_clean();
return $content;
}
$url = $_GET['url'];
if (!isValidUrl($url))
exit(0);
$key = md5($url);
$mmc = memcache_init();
$str = memcache_get($mmc, $key);
if (!$str) {
$image = thumbnailJpeg($url, 320);
$str = imageToString($image);
memcache_set($mmc, $key, base64_encode($str));
}
else {
$image = ImageCreateFromString(base64_decode($str));
}
header("Cache-Control: max-age=31556926");
header("Content-type: image/jpeg");
ImageJpeg($image);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment