preview.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * 此页面用来协助 IE6/7 预览图片,因为 IE 6/7 不支持 base64
  4. */
  5. $DIR = 'preview';
  6. // Create target dir
  7. if (!file_exists($DIR)) {
  8. @mkdir($DIR);
  9. }
  10. $cleanupTargetDir = true; // Remove old files
  11. $maxFileAge = 5 * 3600; // Temp file age in seconds
  12. if ($cleanupTargetDir) {
  13. if (!is_dir($DIR) || !$dir = opendir($DIR)) {
  14. die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  15. }
  16. while (($file = readdir($dir)) !== false) {
  17. $tmpfilePath = $DIR . DIRECTORY_SEPARATOR . $file;
  18. // Remove temp file if it is older than the max age and is not the current file
  19. if (@filemtime($tmpfilePath) < time() - $maxFileAge) {
  20. @unlink($tmpfilePath);
  21. }
  22. }
  23. closedir($dir);
  24. }
  25. $src = file_get_contents('php://input');
  26. if (preg_match("#^data:image/(\w+);base64,(.*)$#", $src, $matches)) {
  27. $previewUrl = sprintf(
  28. "%s://%s%s",
  29. isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
  30. $_SERVER['HTTP_HOST'],
  31. $_SERVER['REQUEST_URI']
  32. );
  33. $previewUrl = str_replace("preview.php", "", $previewUrl);
  34. $base64 = $matches[2];
  35. $type = $matches[1];
  36. if ($type === 'jpeg') {
  37. $type = 'jpg';
  38. }
  39. $filename = md5($base64).".$type";
  40. $filePath = $DIR.DIRECTORY_SEPARATOR.$filename;
  41. if (file_exists($filePath)) {
  42. die('{"jsonrpc" : "2.0", "result" : "'.$previewUrl.'preview/'.$filename.'", "id" : "id"}');
  43. } else {
  44. $data = base64_decode($base64);
  45. file_put_contents($filePath, $data);
  46. die('{"jsonrpc" : "2.0", "result" : "'.$previewUrl.'preview/'.$filename.'", "id" : "id"}');
  47. }
  48. } else {
  49. die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "un recoginized source"}}');
  50. }