꿈을 바구니에 담아 간직하다 보면!!

지금 참 힘들죠? 근데 내일은 지금보다 덜 힘들거예요

힘든 건 오늘만이 아니다. 내일도, 그리고 그 다음 날도 계속될 것이다.

PHP Tip

이미지 src 추출

duaidot 2025. 12. 14. 03:22

<?php
// 이미지 src 추출
preg_match_all('/<img[^>]*src=["\']?([^>"\']+)["\']?[^>]*>/i', $input_text, $img_no);
$img_src = $img_no[1][0] ?? '';

if ($img_src) {
    // 파일명 추출
    $filename = basename(parse_url($img_src, PHP_URL_PATH)); // 쿼리스트링 제거

    // 저장 경로 설정
    $source_path = $target_path = G5_DATA_PATH . '/file/' . $bo_table;
    $file_download = $target_path . '/' . $filename;

    // 디렉토리 없으면 생성
    if (!is_dir($target_path)) {
        mkdir($target_path, 0755, true);
    }

    // 파일이 없으면 복사 시도
    if (!file_exists($file_download)) {
        // 외부 이미지 다운로드
        $image_data = @file_get_contents($img_src);
        if ($image_data !== false) {
            file_put_contents($file_download, $image_data);
        } else {
            // 실패 시 로그 또는 대체 이미지 처리
            error_log("이미지 다운로드 실패: $img_src");
        }
    }

    // 썸네일 생성
    if (file_exists($file_download)) {
        $thumb_src = thumbnail($filename, $source_path, $target_path, "50", "35", false, true);
        $img_src = G5_DATA_URL . '/file/' . $bo_table . '/' . $thumb_src;
    }
}
?>