본문 바로가기
Tip & Tech/php

간단한 PHP 파일 업로드, 다운로드 구현

by 변기환 2011. 7. 28.

PHP를 이용한 간단한 파일 업로드, 다운로드를 가능하게 하는 소스다. 요즘은 함수나 클래스로 구현하는 경우가 많지만, 간단하게 사용할 수 있도록 별다른 기능을 넣지는 않았다.

이 소스를 기본으로 다중파일 업로드와 업로드 된 파일을 다운로드 받을 시, 파일 확장자를 체크하여 이미지 파일이면 다운로드 받지 않고 브라우저에서 직접 보이도록 하는 기능은 직접 구현하기 바란다.

Up_Load_Form.html (파일 업로드 화면)

<form name="form1" method="post" enctype="multipart/form-data" action="File_Upload.php">
<table width="600" border="0" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
   <td colspan="2" bgcolor="#FFFFFF">PHP를 이용한 파일업로드 기능의 구현</td>
</tr>
<tr>
   <td width="150" align="center" bgcolor="#FFFFFF">업로드할 파일</td>
   <td width="464" bgcolor="#FFFFFF"><input type="file" name="myFile" size="60" /></td>
</tr>
<tr>
   <td colspan="2" bgcolor="#FFFFFF"><input type="submit" value="파일 업로드" />
   <input type="reset" value="취소" /></td>
</tr>
</table>
</form>
File_Upload.php (파일 업로드)
<?
//업로드한 파일을 저장할 디렉토리
$save_dir = "files/";

//파일이 HTTP POST 방식을 통해 정상적으로 업로드되었는지 확인한다.
if(is_uploaded_file($_FILES["myFile"]["tmp_name"]))
{
   echo "업로드한 파일명 : ".$_FILES["myFile"]["name"] ."<br />";
   echo "업로드한 파일의 크기 : ".$_FILES["myFile"]["size"] ."<br />";
   echo "업로드한 파일의 MIME Type : ".$_FILES["myFile"]["type"] ."<br />";
   echo "임시 디렉토리에 저장된 파일명 : ".$_FILES["myFile"]["tmp_name"]."<br />";

   //파일을 저장할 디렉토리 및 파일명
   $dest = $save_dir . $_FILES["myFile"]["name"];

   //파일을 지정한 디렉토리에 저장
   if(!move_uploaded_file($_FILES["myFile"]["tmp_name"], $dest))
   {
      die("파일을 지정한 디렉토리에 저장하는데 실패했습니다.");
   }
}
?>

필자의 경우 파일 중복을 피하기 위해서
$fn = $_FILES["myFile"]["name"];
$fn = mktime()."^".$fn;
DB 삽입시 파일명을 (시간 + ^+ 파일명) 형태로 가공해서 넣었다. 나중에 다운로드를 구현할 때 "^" 기준으로 잘라내면 뒷부분이 원본 파일 이름이 된다.

다운로드 링크

<a href="javascript:down('파일명')">다운로드</a>
<script>
function down(fileName)
{
   url = "Down_Load.php
?fileName="+fileName;;
   location.href = url;
}
</script>

Down_Load.php (다운로드 받는 페이지 구현)
<?
$fileName = $_REQUEST[fileName];
$DownloadPath = "./files/".$fileName; // 파일 경로
$fileTmp = strstr($fileName, '^'); // 파일명 임시저장(앞의 '^'를 제거
$DownFile = substr($fileTmp, 2);

Header("Content-Type: file/unknown");
Header("Content-Disposition: attachment; filename=". $DownFile);
Header("Content-Length: ".filesize("$DownloadPath"));
header("Content-Transfer-Encoding: binary ");
Header("Pragma: no-cache");
Header("Expires: 0");
flush();

if ($fp = fopen("$downloadPath", "r"))
{
   print fread($fp, filesize("$DownloadPath"));
}
fclose($fp);
?>


'Tip & Tech > php' 카테고리의 다른 글

iframe을 이용한 중복체크  (1) 2012.04.27
PHP- 파일 다운로드시 속도 제한하기  (0) 2011.07.29
PHP HomePage Builder  (0) 2010.07.14
PHP HomePage Builder - 홈페이지의 구조 알기  (0) 2010.07.13
PHP Text Files 핸들링  (0) 2010.06.27

댓글