<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);

$posLastSlash = strrpos(@$_SERVER['PATH_INFO'], "/");
$path = "upl".($posLastSlash!==false ? substr(@$_SERVER['PATH_INFO'], 0, $posLastSlash+1) : "/");
$file = substr(@$_SERVER['PATH_INFO'], $posLastSlash+1);

$oriname = $path.$file;

if (!file_exists($oriname)) {
  http_response_code(404);
} else {
  $mime = mime_content_type($oriname);
  $type = exif_imagetype($oriname);
  $ext = substr(image_type_to_extension($type),1);
  $name = $oriname;
  http_response_code(200);
  if (isset($_GET["h"])) {
    $thumbspath = $path."__thumbs/";
    if (!file_exists($thumbspath)) {
      mkdir($thumbspath, 0770, true);
    }
    $newHeight = intval($_GET["h"]);
    $name = $thumbspath.$newHeight."p_".$file;
    if (!file_exists($name)) {
      $image_create_func = "imagecreatefrom".$ext;
      $image_save_func = "image".$ext;
      
      $img = $image_create_func($oriname);
      list($width, $height) = getimagesize($oriname);
      if ($height<=$newHeight) {
        $newHeight = $height;
        $newWidth = $width;
      }
      $newWidth = ($width / $height) * $newHeight;
      $tmp = imagecreatetruecolor($newWidth, $newHeight);
      imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
      
      $image_save_func($tmp, $name);
  } }
  
  $fp = fopen($name, 'rb');
  header("Content-Type: " . $mime);
  header("Content-Length: " . filesize($name));
  
  fpassthru($fp);
}
