. */ const POSTER_DIR = './image_cache/poster'; const BACKDROP_DIR = './image_cache/backdrop'; const POSTER_SIZE = 'w92'; const BACKDROP_SIZE = 'w300'; const BASE_IMAGE_URL = 'https://image.tmdb.org/t/p/'; function validate_input($url, $image_type) { if (preg_match('/[^a-z0-9_\.]/i', $url) || !preg_match('/\.(png|jpeg|jpg)$/', $url)) { header('Content-Type: text/plain'); echo 'invalid image name: "' . @$raw_query . '"'; die(); } if ($image_type !== 'poster' && $image_type !== 'backdrop') { header('Content-Type: text/plain'); echo 'invalid image type: "' . @$raw_image_type . '"'; die(); } } function cache_image($remote_url, $fs_dir, $fs_path, &$errors) { if (is_writable($fs_dir)) { $data = @file_get_contents($remote_url); if ($data) { if (file_put_contents($fs_path, $data) === false) { $errors[] = __FUNCTION__ . ", error writing file, $fs_path"; return false; } } else { $errors[] = __FUNCTION__ . ", error fetching url: $remote_url"; return false; } } else { $errors[] = __FUNCTION__ . ", cannot write path: $fs_path"; return false; } return true; } function log_errors($errors) { header('Content-Type: text/plain'); foreach ($errors as $err) echo $err . "\n"; die(); } function display_local_image($fs_path) { $extension_mapping = [ 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png' ]; $content_type = $extension_mapping[pathinfo($fs_path, PATHINFO_EXTENSION)]; header("Content-Type: $content_type"); readfile($fs_path); } $raw_query = @$_GET['image_url']; $image_name = basename($raw_query); $raw_image_type = @$_GET['image_type']; $image_type = basename(strtolower($raw_image_type)); validate_input($image_name, $image_type); $local_dir = ($image_type == 'poster') ? POSTER_DIR : BACKDROP_DIR; $size_part = ($image_type == 'poster') ? POSTER_SIZE : BACKDROP_SIZE; $local_path = $local_dir . '/' . $size_part . '/' . $image_name; $remote_url = BASE_IMAGE_URL . $size_part . '/' . $image_name; $errors = []; if (is_file($local_path)) { display_local_image($local_path); } elseif (empty($errors)) { if (cache_image($remote_url, $local_dir, $local_path, $errors)) display_local_image($local_path); else log_errors($errors); } else { log_errors($errors); } ?>