카테고리:

2 분 소요

소스 코드

php로 여러가지를 개발하다 보면, 사용자가 파일을 업로드 해야 할 상황이 있다.

아래는 php8 에서 사진 파일을 업로드하는 예제이다.

  • index.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>사진 업로드</title>
</head>
<body>
    <form action="upload.php" method="POST" enctype="multipart/form-data">
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload Image" name="submit">
    </form>
</body>
</html>
  • upload.php
// 업로드 디렉토리를 설정합니다.
$uploadDir = "uploads/"; // 업로드 디렉토리 경로

$maxFileSize = 5 * 1024 * 1024; // 5MB

// 업로드된 파일의 정보를 가져옵니다.
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];

// 파일 확장자를 체크하고 허용되는 확장자를 지정합니다.
$allowedExtensions = ["jpg", "jpeg", "png", "gif"];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

if (in_array($fileExtension, $allowedExtensions)) {
  // 파일 크기를 체크하고 원하는 크기로 제한합니다.
  if ($fileSize <= $maxFileSize) {
    // 새로운 파일 이름을 생성합니다.
    $newFileName = uniqid() . "." . $fileExtension;
    $uploadPath = $uploadDir . $newFileName;

    // 임시 파일의 경로를 UTF-8로 변환합니다.
    $utf8TmpFileName = mb_convert_encoding($fileTmpName, 'UTF-8', 'auto');

    // 파일을 이동시킵니다.
    if (move_uploaded_file($utf8TmpFileName, $uploadPath)) {
      echo "파일 업로드 성공: " . $newFileName;
    } else {
      echo "파일 업로드 실패.";
    }
  } else {
    echo "파일 크기가 너무 큽니다. 최대 파일 크기는 " . ($maxFileSize / (1024 * 1024)) . "MB입니다.";
  }
} else {
  echo "지원하지 않는 파일 형식입니다. jpg, jpeg, png, gif 파일만 허용됩니다.";
}

임시 파일의 경로를 UTF-8로 변환하는 과정을 거치지 않으면 사용자가 한글이 포함된 파일을 업로드할 때 오류가 발생한다. 따라서 iconv나 mb_convert_encoding를 사용하는데 아래의 글을 참조하여 바꿔 사용하면 된다.

https://stackoverflow.com/questions/8233517/what-is-the-difference-between-iconv-and-mb-convert-encoding-in-php

태그: $_FILES, mb_convert_encoding, move_uploaded_file, php, php8, upload, utf-8, 깨짐, 업로드, 한글

업데이트: