반응형

PHP로 FILE 업로드  

필요한 파일 

- files( 파일이 저장될 파일)

- index.php(파일 리스트)

- delete.php(삭제)

- download.php(파일 다운)

- table.php(게시판 작성 양식)

- write.php(파일이 db에 저장되는 것을 처리)

- view.php(파일의 내용을 볼수 있는 곳)



download.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
 
    header("Content-type: text/html; charset=utf-8");
 
    if(!$_GET['num'])
    {
        echo "<script>alert('이상하게 접근하셨습니다;;');";
        echo "history.back();</script>";
    }
    
    $host = 'localhost';
    $user = 'root';
    $pw = '111111';
    $dbName = 'opentutorials';
    $mysqli = new mysqli($host$user$pw$dbName);
    
 
    if(mysqli_connect_errno())
        {
            echo "DB connect error";
        
            exit;
        }
    
    $sql = "select name, hash from a where num=".$_GET['num'];
    $res = $mysqli->query($sql);
    if(!$res)
    {
        echo "query error";
        exit;
    }
    $res = $res->fetch_assoc();
    
    $dir = "./files/";
    $filename = $res['name'];
    $filehash = $res['hash'];
    
    if(file_exists($dir.$filehash))
    {
            header("Content-Type: Application/octet-stream");
            header("Content-Disposition: attachment; filename=".$filename);
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".filesize($dir.$filehash));
 
            $fp = fopen($dir.$filehash"rb");
            while(!feof($fp))
            {
                echo fread($fp1024);
            }
            fclose($fp);
            
            $sql = "update a set down=(down+1) where num=".$_GET['num'];
            $res = $mysqli->query($sql);
            if(!$res)
            {    
                echo "down counter update error";
                exit;
            }
    }
    else
    {
            echo "<script>alert('파일이 없습니다.);";
            echo "history.back();</script>";
            exit;
    }
 mysqli_close($mysqli);
    
?>
cs


 if(!$_GET['num'])
    {
        echo "<script>alert('이상하게 접근하셨습니다;;');";
        echo "history.back();</script>";
    }

만약 num으로 받은 것이 없다면,
이상하게 접근하셨습니다.라고 띄우고, 뒤페이지로 돌아갑니다.


   $host = 'localhost';
    $user = 'root';
    $pw = '111111';
    $dbName = 'opentutorials';
    $mysqli = new mysqli($host$user$pw$dbName);

db에 연동시킵니다.


 if(mysqli_connect_errno())
        {
            echo "DB connect error";
        
            exit;
        }

mysqli_connect_errno : 어떤 경우 mysqli_connect_errno () 함수는, 마지막 연결 오류에서 오류 코드를 반환합니다.

오류가 있을시 오류 코드 값을 돌려줍니다.


 $sql = "select name, hash from a where num=".$_GET['num'];
    $res = $mysqli->query($sql);
    if(!$res)
    {
        echo "query error";
        exit;
    }
    $res = $res->fetch_assoc();


쿼리문으로 num이 동일한 a 테이블의 name과 hash를 선택합니다.

결과를 res 변수에 저장합니다.


결과가 없다면 querry error를 내보냅니다.

결과가 있다면 res변수에 저장된것을 배열로 저장합니다.



필드명name

age

저장값

김영수

24

 

1. fetch_array

이 함수는 결과를 배열로 뽑아내는데, 번호로 된 배열과 필드 이름으로 된 배열 두가지가 동시에 생성된다.

위와 같은 테이블에서 데이터를 뽑아내면 fetch_array 를 통해 뽑아낸 배열의 구조는 다음과 같다.

Array (

    [0] => 김영수

    [name] => 김영수

    [1] => 24

    [age] => 24

)


2. fetch_assoc

이 함수는 필드 이름으로 된 배열로만 저장한다.

Array (

     [name] => 김영수

     [age] => 24

)


3. fetch_row

이 함수는 숫자로 된 배열로 저장한다.

Array (

     [0] => 김영수

     [1] => 24

)


4. fetch_object

이 함수는 배열이 아닌 객체로 결과값을 받아온다.

stdClass Object (

    [name] => 김영수

    [age] => 24

)


   $dir = "./files/";
    $filename = $res['name'];

    $filehash = $res['hash'];


 $dir = "./files/"; 은 파일이 저장되어 있는 디렉토리명을 dir변수에 저장시킵니다.

실제 파일 이름과 실제 서버에 저장된 파일이름 (해시값)을 변수로 저장시킵니다.


    if(file_exists($dir.$filehash))
파일의 존재 유무를 검사합니다. 없다면 else문을 실행시킵니다.
 else
    {
            echo "<script>alert('파일이 없습니다.);";
            echo "history.back();</script>";
            exit;
    }


파일이 있다면 아래를 실행시킵니다. 


 {
            header("Content-Type: Application/octet-stream");
            header("Content-Disposition: attachment; filename=".$filename);
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".filesize($dir.$filehash));
 
            $fp = fopen($dir.$filehash"rb");
            while(!feof($fp))
            {
                echo fread($fp1024);
            }
            fclose($fp);
            
            $sql = "update ftp set down=(down+1) where num=".$_GET['num'];
            $res = $mysqli->query($sql);
            if(!$res)
            {    
                echo "down counter update error";
                exit;
            }
    }




            header("Content-Type: Application/octet-stream");
                   디폴트 미디어 타입은 운영체제 종종 실행파일, 다운로드를 의미
            header("Content-Disposition: attachment; filename=".$filename);
                 파일이 저장할때 이름을 지정한다 filename변수의 값을 쓴다.
            header("Content-Transfer-Encoding: binary");
                 바이너리 형태임을 명시해준다.
            header("Content-Length: ".filesize($dir.$filehash));
                 파일 사이즈를 명시해준다. 이렇게 하면 브라우저가 파일 다운로드시 남은 시간을 계산 할 수 있다.



$fp = fopen($dir.$filehash"rb");
            while(!feof($fp))
            {
                echo fread($fp1024);
            }
            fclose($fp);


      실제로 다운할 파일을 fopen으로 엽니다. 또한 바이너리 파일이므로  rb(read binary) 를 지정합니다.

      또한 while문을 써서 

      파일의 끝이 아닐때까지

      1024바이트씩 파일을 읽어들입니다.

      파일을 닫습니다.


            $sql = "update a set down=(down+1) where num=".$_GET['num'];
     파일 다운로드의 조회수를 +1 하는 쿼리문입니다. 





delete.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php    
 
    if(!$_GET['num'])
    {
        echo "<script>alert('이상하게 접근하셨습니다;;');";
        echo "history.back();</script>";
    }
    
   $host = 'localhost';
    $user = 'root';
    $pw = '111111';
    $dbName = 'opentutorials';
    $mysqli = new mysqli($host$user$pw$dbName);
    
    
   if(mysqli_connect_errno())
        {
            echo "DB connect error";
        
            exit;
        }
    
    $sql = "select hash from a where num=".$_GET['num'];
    $res = $mysqli->query($sql);
    if(!$res)
    {
        echo "select query error";
        exit;
    }
    $res = $res->fetch_assoc();
    
    $dir = "./files/";
    $filehash = $res['hash'];
    
    if(!unlink($dir.$filehash))
    {
            echo "file delete error";
            exit;
    }
    
    $sql = "delete from a where num=".$_GET['num'];
    $res = $mysqli->query($sql);
    if(!$res)
    {
        echo "delete query error";
        exit;
    }
    
    echo "<script>alert('파일이 삭제되었습니다.');";
    echo "history.back();</script>";
 
 mysqli_close($mysqli);
    
?>
cs



 if(!unlink($dir.$filehash))
    {
            echo "file delete error";
            exit;
    }


unlink함수는 해당위치의 파일을 삭제합니다.

업로드할때 파일이름을 해시값으로 저장했기 때문에, 해시명을 넣어줍니다.



 $sql = "delete from a where num=".$_GET['num'];

sql에 있는 db도 삭제하기 위하여 이 쿼리문을 써줍니다.



반응형

+ Recent posts