Блог

PHP: получить изображение по ссылке

Вывести изображение по ссылки через header.

<?php
class GetImage
{
	public static $types = array('jpeg', 'jpg', 'png', 'gif');

	public function getImage($name = false)
	{
		$path = false;
		if(self::checkUrl($name)) {
			$path = $name;
		}

		$type = strtolower(pathinfo($path, PATHINFO_EXTENSION));
		$content = @file_get_contents($path);
		if(!$type) {
			$type = str_replace('Content-Type: image/', '', $http_response_header[5]);
		}
		if(!in_array($type, self::$types)) {
			header("HTTP/1.0 404 Not Found");
			header("Status: 404 Not Found");
			return;
		}

		$content = @file_get_contents($path);
		if($content == false) {
			header("HTTP/1.0 404 Not Found");
			header("Status: 404 Not Found");
			return;
		}

		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false);
		header("Content-type: image/$type");
		header("Content-Length: ". strlen($content));

		print $content;
		exit;
	}

	protected function checkUrl($url)
	{
		$check = preg_match("/^(https?|ftp):///", $url);
		if($check) {
			return true;
		}

		return false;
	}
}

$img = new GetImage('https://lh3.googleusercontent.com/-V7pJ7AT6SVo/RrwM7eN56wI/AAAAAAAAB2A/rk6opdWEr4I/s640');
?>