본문 바로가기
PHP

[PHP] 이미지 업로드 및 업로드한 이미지 보기

by teamnova 2024. 2. 3.

안녕하세요 오늘은 이미지를 업로드하고 업로드한 이미지들을 확인하는 방법에 대해 알아보겠습니다.

 

 

upload.php 파일에 다음과 같이 코드를 작성해주세요

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
    $target_dir = "./uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // 파일이 이미지인지 확인
    if(getimagesize($_FILES["image"]["tmp_name"]) !== false) {
        // 이미지 파일인 경우, 서버에 업로드
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
            echo "파일 ". htmlspecialchars(basename($_FILES["image"]["name"])). " 업로드 성공.";
        } else {
            echo "파일 업로드에 실패했습니다.";
        }

    } else {
        echo "이미지 파일이 아닙니다.";
    }
}
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>이미지 업로드</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        이미지 선택: <input type="file" name="image" id="fileToUpload">
        <button type="submit" name="submit">업로드</button>
    </form>

    <a href="gallery.php">업로드된 이미지 보기</a>
</body>
</html>

 

 

gallery.php 파일에 다음과 같이 코드를 작성해주세요\

<?php
$images = glob("uploads/*.*");
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>이미지 갤러리</title>
</head>
<body>
    <h2>업로드된 이미지</h2>
    <div>
        <?php
        foreach($images as $image) {
            echo "<img src='".htmlspecialchars($image)."' style='width:200px;height:auto;'>";
        }
        ?>
    </div>
</body>
</html>

 

 

 

해당 파일이 위치해 있는 폴더에 uploads 라는 새로운 폴더를 생성해주세요

 이미지들을 해당 폴더에 저장할 예정입니다.  

 

위와 같이 구현하면 다음과 같은 결과를 얻을 수 있습니다.