관리 메뉴

투덜이 개발자

[PHP] 이미지 URL 검증 함수 본문

카테고리 없음

[PHP] 이미지 URL 검증 함수

엠투 2025. 4. 4. 10:05
반응형

* 첫번째

class ImageValidator {
	
	public static function httpImageUrl($url)
	{
		if (strpos($url, 'http://') === false and strpos($url, 'https://') === false) {
			$url = _WEB_BASE_DIR . $url;
		}
		return $url;
	}
	
	// 이미지 url 체크
	public static function isImageUrlValid($imageUrl): bool
	{
		$imageUrl = self::httpImageUrl($imageUrl);
		// echo "imageUrl : {$imageUrl} <br>";
		
		$headers = @get_headers($imageUrl);
		
		// Check if URL exists and is accessible
		if ($headers) {
			if (strpos($headers[0], "200") or strpos($headers[0], "301")) {
				// Check if the content type indicates an image
				if (@strpos($headers['Content-Type'], 'image') !== false) {
					return true;
				}
				// Check if URL is a direct link to an image file
				$image_info = @getimagesize($imageUrl);
				if ($image_info !== false) {
					return true;
				}
			}
		}
		
		return false;
	}
}

 

 

* 두번째

getimagesize 함수는 이미지 파일의 크기 및 유형 정보를 가져오기 위해 파일을 다운로드하므로

, 큰 이미지 파일의 경우 성능에 영향을 줄 수 있습니다.

그래서 curl 함수를 사용하여 헤더를 가져오면 더 많은 옵션과 오류 처리를 할수 있고 속도를 줄일 수 있다.

class ImageValidator {
	
	public static function httpImageUrl($url)
	{
		if (strpos($url, 'http://') === false and strpos($url, 'https://') === false) {
			$url = _WEB_BASE_DIR . $url;
		}
		return $url;
	}
	
	public static function isImageUrlValid($imageUrl): bool
	{
		$imageUrl = self::httpImageUrl($imageUrl);
		
		if (function_exists('curl_init')) {
			// curl 사용
			$ch = curl_init($imageUrl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HEADER, true);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 리디렉션 따라가기
			curl_setopt($ch, CURLOPT_NOBODY, true); // body 없이 헤더만 요청
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // SSL 인증서 검증 건너뛰기 (개발 환경에서만 사용 권장)
			curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 타임아웃 설정
			
			$response = curl_exec($ch);
			$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
			curl_close($ch);
			
			if ($response === false) {
				return false; // curl 오류 발생
			}
			
			if ($httpCode >= 200 && $httpCode < 300) {
				// Content-Type 확인 (더 엄격한 검증)
				if (strpos($contentType, 'image') !== false) {
					return true;
				}
			}
			return false;
		} else {
			// curl을 사용할 수 없는 경우 get_headers, getimagesize 사용
			$headers = @get_headers($imageUrl);
			if ($headers) {
				if (strpos($headers[0], "200") !== false || strpos($headers[0], "301") !== false) {
					if (@strpos($headers['Content-Type'], 'image') !== false) {
						return true;
					}
					$image_info = @getimagesize($imageUrl);
					if ($image_info !== false) {
						return true;
					}
				}
			}
			return false;
		}
	}
}

 

* 세번째

가독성이 향상되었으며, 불필요한 코드가 제거되었습니다.

curl_setopt_array 및 삼항 연산자를 사용하여 코드의 길이를 줄였습니다.

getimagesize를 제거하여 성능을 향상시켰습니다.

class ImageValidator {
	public static function httpImageUrl($url) {
		return (strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0)
			? $url
			: _WEB_BASE_DIR . $url;
	}
	
	public static function isImageUrlValid($imageUrl): bool {
		$imageUrl = self::httpImageUrl($imageUrl);
		
		if (function_exists('curl_init')) {
			$ch = curl_init($imageUrl);
			curl_setopt_array($ch, [
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_HEADER => true,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_NOBODY => true,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_TIMEOUT => 10
			]);
			
			curl_exec($ch);
			$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
			curl_close($ch);
			
			return ($httpCode >= 200 && $httpCode < 300) && (strpos($contentType, 'image/') !== false);
		} else {
			$headers = @get_headers($imageUrl, 1);
			if ($headers && isset($headers["Content-Type"])) {
				return strpos($headers["Content-Type"], "image/") !== false;
			}
			return false;
		}
	}
}

 

* 사용예시

// 사용 예시
define('_WEB_BASE_DIR', 'http://yourdomain.com/');

$imageUrl = '/images/test.jpg';
$isValid = ImageValidator::isImageUrlValid($imageUrl);

if ($isValid) {
	echo "이미지 URL이 유효합니다.";
} else {
	echo "이미지 URL이 유효하지 않습니다.";
}

$imageUrl2 = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
$isValid2 = ImageValidator::isImageUrlValid($imageUrl2);

if ($isValid2) {
	echo "<br> 이미지 URL이 유효합니다.";
} else {
	echo "<br> 이미지 URL이 유효하지 않습니다.";
}

$imageUrl3 = "https://www.google.com";
$isValid3 = ImageValidator::isImageUrlValid($imageUrl3);

if ($isValid3) {
	echo "<br> 이미지 URL이 유효합니다.";
} else {
	echo "<br> 이미지 URL이 유효하지 않습니다.";
}
반응형