Loading...
PHP를 통한 이미지 업로드 + 미리보기 처리
REDINFO
약 1년전 2023-05-16 00:47:18

이미지업로드는 웹상에서는 많이 사용하는 기능으로 이미지를 업로드 후 PHP를 통해 파일 또는 DB를 통해 주로 저장한다.  이번편에서는 가장 기본적인 파일 업로드 후 PHP를 통해 저장 후 미리보기 프로그램 소스에 대해 알아보도록 하자. 

 

1. 파일생성 FORM 을 작성 | file.php

아래와 같이 file 을 업로드 하는 기능을 가진 form을 생성해 보자 

<form id="form" action="upload.php" method="post" enctype="multipart/form-data">
	<h1>이미지 업로드 파일 미리보기</h1>
	<input type="file" name="file" value="" accept="image/*">
	<hr />
	<label><input type="checkbox" name="fileUpload" value="Y"> 파일 업로드</label>
	<hr />
	<input type="submit" value="전송">
</form>
  • form 영역을 보면 action 은 upload.php 로 연결되는 서버처리 url이다. 
  • input 은 총 세가지로 file , checkbox, submit 이 있다. 

 

2. 전송된 이미지 파일을 처리할 서버 프로그램 생성 | upload.php

그다음으로 서버에서는 전송된 파일을 처리하여 저정 후 이미지를 바로 볼 수 있도록 처리해보자.

<?php 
try{
	if( $_FILES['file']['size'] < 1){ die('정상 파일이 아님'); }

	$resource = $_FILES['file']['tmp_name'];
	$mimeType = @image_type_to_mime_type(exif_imagetype($resource)); // OR => getimagesize($resource) 을통해 ['mime'] 으로 가져올 수 있다. 

	if( empty($mimeType)){ throw new Exception("이미지 파일이 아님", __LINE__); }

	// 압축없이 생성
	if ($mimeType == 'image/jpeg') {
	$setFunction = ''; // 이미지 출력함수 초기화
		@ini_set('gd.jpeg_ignore_warning', 1); // 용량이 클경우 오류방지
		$image = @imagecreatefromjpeg($resource); // 예외처리
		$setFunction = 'imagejpeg'; // 파라미터참조: https://www.php.net/manual/en/function.imagejpeg
	}elseif ($mimeType == 'image/gif'){
		$image = imagecreatefromgif($resource);
		$setFunction = 'imagegif'; // 파라미터참조: https://www.php.net/manual/en/function.imagegif.php
	}elseif ($mimeType == 'image/png'){
		$image = imagecreatefrompng($resource);
		$setFunction = 'imagepng'; // 파라미터참조: https://www.php.net/manual/en/function.imagepng.php
	}else{
		throw new Exception("지원하지 않는 이미지 확장명입니다.", __LINE__);
	}

	if( empty($image)){ throw new Exception("이미지 생성에 실패하였습니다.", __LINE__); }

	// 파일 업로드
	$filename = null;
	if( isset($_POST['fileUpload']) && $_POST['fileUpload'] == 'Y'){
		// 저장될 디렉토리 (퍼미션이 있어야함)
		$dir = __DIR__."/files"; 

		// 디렉토리 있는지 
		if( !is_dir($dir)){ throw new Exception("저장 디렉토리가 존재하지 않음", __LINE__); }

		// 디렉토리 권한
		if( substr(sprintf('%o', fileperms($dir)), -4) != '0777'){
			throw new Exception("저장될 디렉토리에 퍼미션 없음", __LINE__);
		}

		// 저장 파일이름
		$filename = $dir."/".md5(time().uniqid()).".".end(explode(".",$_FILES['file']['name']));

		// 이미지 저장
		ob_start();
		$setFunction($image,$filename); // 3번째 파라미터는 퀄러티
		ob_end_clean();
	}

	// 이미지 미리보기
	header("Content-Type: ".$mimeType);
	$setFunction($image);
	imagedestroy($image);

}catch(Exception $e){

	// 에러 결과 출력
	echo 'Code: '.$e->getCode();
	echo '<hr/>';
	echo 'Message: '.$e->getMessage();
}
  • 주석에도 설명이 있듯이 맨 처음 업로드된 파일을 체크한다. 
  • 이미지 파일 mime type 을 체크한다. (jpeg,jpg,png,gift) 
  • 이미지를 처리하기 위해 이미지 리소스를 생성한다.
  • 이미지 리소스 생성과 함께 최종 이미지를 출력할 함수를 변수에 초기화 한다. 
  • 파일업로드 체크박스 유무에 따라 파일을 저장할지 체크한다. 
  • 파일업로드는 반드시 업로드될 디렉토리가 있어야하고 디렉토리 권한이 0777 로 설정이 되어있어야한다.
  • 최종적으로 이미지 함수를 통해 이미지를 출력해준다.

위와 같이 가장 기본적인 이미지 업로드 처리에대해 알아보았다. 참고로 파일저장의 경우 위 방법 말고도 `move_uploaded_file` 함수를 통해 처리할 수 있으니 시간날때 소스코드를 수정하여 테스트해보는 것도 좋다. 

 

이 포스트글이 도움이 되었나요?
6
카테고리 연관글

Comment

댓글작성

0(500) | 1(30)