Created
September 25, 2015 13:02
-
-
Save oxyflour/8eb67e5e760d532804c7 to your computer and use it in GitHub Desktop.
php script to cache images with memcache in Sina App Engine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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