Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- wkhtmltopdf 실행 오류
- 비밀번호검증정규식
- apple push notification service (apns) is changing
- apache mod rewrite
- bootstrap modal
- libxrender1
- mariadb upgrade
- 파라미터 & 오류
- PHP 구글 OTP 연동
- httpd.conf 보안 설정
- 숫자 3자리(천단위) 마다 콤마 찍기
- php 배열제거
- 구글 OTP 인증
- bootstrap
- html pdf 변환
- mysql root 비밀번호 변경
- 아파치 웹 서버의 정보 숨기기
- sha-2 root
- PHP 정규식 예제
- group_concat 구분자
- 비밀번호정규식
- PHP 구글 OTP 인증
- usb efi 시스템 파티션 삭제
- 자바스크립트비밀번호검증
- modsecurity 설치
- php 이미지 url 검증 함수
- javascript
- (using password: YES)" when trying to connect
- mysqldump: Got error: 1045
- 우분투 mysql 비밀번호 없이 로그인 될때
Archives
- Today
- Total
투덜이 개발자
[PHP] 이미지 URL 검증 함수 본문
반응형
* 첫번째
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이 유효하지 않습니다.";
}
반응형