[php] PHP를 통한 파일 업로드와 썸네일 생성

파일 업로드와 썸네일 생성은 웹 애플리케이션에서 자주 사용되는 기능입니다. 이 기능을 PHP를 사용하여 구현하는 방법에 대해 알아보겠습니다.

파일 업로드

사용자가 웹 페이지를 통해 파일을 업로드할 수 있도록 하려면, HTML 폼을 생성해야 합니다. 폼에 enctype="multipart/form-data" 속성을 추가하여 파일을 업로드할 수 있도록 합니다.

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

다음으로, PHP 스크립트를 작성하여 파일을 업로드합니다. move_uploaded_file 함수를 사용하여 업로드된 파일을 지정된 디렉토리로 이동시킬 수 있습니다.

$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile);

썸네일 생성

이제 업로드한 이미지 파일을 사용하여 썸네일을 생성해보겠습니다. 썸네일을 생성하기 위해 GD 라이브러리를 사용합니다. 먼저, 썸네일을 생성하기 위한 함수를 작성합니다.

function createThumbnail($sourceFile, $targetFile, $width, $height) {
    list($sourceWidth, $sourceHeight) = getimagesize($sourceFile);
    $sourceImage = imagecreatefromjpeg($sourceFile);
    $thumbnailImage = imagecreatetruecolor($width, $height);
    imagecopyresized($thumbnailImage, $sourceImage, 0, 0, 0, 0, $width, $height, $sourceWidth, $sourceHeight);
    imagejpeg($thumbnailImage, $targetFile);
    imagedestroy($sourceImage);
    imagedestroy($thumbnailImage);
}

이제 파일 업로드와 썸네일 생성 기능을 결합하여 업로드된 이미지 파일에 대한 썸네일을 생성합니다.

$uploadedFile = "uploads/" . $_FILES["file"]["name"];
$thumbnailFile = "thumbnails/" . $_FILES["file"]["name"];
createThumbnail($uploadedFile, $thumbnailFile, 100, 100);

이제 PHP를 사용하여 파일 업로드와 썸네일 생성하는 방법에 대해 알아보았습니다.

레퍼런스: