반응형

PHP로 FILE 업로드  

필요한 파일 

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

- index.php(파일 리스트)

- delete.php(삭제)

- download.php(파일 다운)

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

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

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



htdocs.zip




htdocs.zip
0.22MB
반응형
반응형

PHP로 FILE 업로드  

필요한 파일 

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

- index.php(파일 리스트)

- delete.php(삭제)

- download.php(파일 다운)

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

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

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


subject부분을 클릭했을 때 링크로 걸리도록 한 view.php 파일입니다.

view.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
 
 
 
<html>
 <meta charset="utf-8"/>
    <title>게시판</title>
 
<?php
 
$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 * from a where num=".$_GET['num'];
       $res = $mysqli->query($sql);
     $res = $res->fetch_assoc();
    



 
    echo "id:" .$res['id'];
    echo '<p/>';
 
 
 
    echo "subject:" .$res['subject'];
    echo '<p/>';
 
 
    echo "memo:" .$res['memo'];
    echo '<p/>';
 
    echo "<td align='left'>
          <a href='./download.php?num=".$res['num']."'>".$res['name']."</a></td>";
    
     mysqli_close($mysqli);
 
 ?>
   
 
 
 
</html>
 
 
 

cs




    $sql = "select * from a where num=".$_GET['num'];
       $res = $mysqli->query($sql);
     $res = $res->fetch_assoc();
    

        num이 일치하는 조건을 가진 데이터의 모든 데이터를 골라 배열로 저장시킵니다.





결과입니다.



반응형
반응형

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도 삭제하기 위하여 이 쿼리문을 써줍니다.



반응형
반응형

PHP로 FILE 업로드  

필요한 파일 

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

- index.php(파일 리스트)

- delete.php(삭제)

- download.php(파일 다운)

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

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

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


index.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
<html>
<head>
    <meta charset="utf-8"/>
    <title>file list</title>
</head>
<body>
<?php
$host = 'localhost';
$user = 'root';
$pw = '111111';
$dbName = 'opentutorials';
$mysqli = new mysqli($host, $user, $pw, $dbName);
 if(mysqli_connect_errno())
        {
            echo "DB connect error";
        }
        
        $sql = "select * from a";
        $res = $mysqli->query($sql);
        $num_result = $res->num_rows;
    ?>
    
    
    
    <table border='1' align="center">
        <thead>
            <tr>
                <th width="50">NUM</th>
                <th width="250">FILE</th>
                <th width="200">TIME</th>
                <th width="50">id</th>
                <th width="70">subject</th>
                <th width="250">memo</th>
                <th width="70">DOWN</th>
                <th width="50">DEL</th>
                
 
            </tr>
        </thead>
        <tbody>
            <?php
                for($i=0; $i<$num_result; $i++)
                {
                    $row = $res->fetch_assoc();
                    echo "<tr>";
                    echo "<td align='center'>".$row['num']."</td>";
                    echo "<td align='left'>
                <a href='./download.php?num=".$row['num']."'>".$row['name']."</a></td>";
                    echo "<td align='center'>".$row['time']."</td>";
                    echo "<td align='center'>".$row['id']."</td>";
                    echo "<td align='center'>
                <a href='./view.php?num=".$row['num']."'>".$row['subject']."</a></td>";    
                    echo "<td align='center'>".$row['memo']."</td>";
                    echo "<td align='center'>".$row['down']."</td>";    
                    echo "<td align='center'>
                <a href='./delete.php?num=".$row['num']."'>DEL</a></td>";                    
                    echo "</tr>";
                }
              mysqli_close($mysqli);
 
              
            ?>
            <input type = "button" name = "table" value ="글쓰기" onclick = "location.href='table.php'";>
        </tbody>
cs

이것인데요........ㅠㅠㅠ 저게뭐람... 

<?php
$host = 'localhost';
$user = 'root';
$pw = '111111';
$dbName = 'opentutorials';
$mysqli = new mysqli($host, $user, $pw, $dbName);
 if(mysqli_connect_errno())
        {
            echo "DB connect error";
        }
        

sql 연동 부분입니다.


$sql = "select * from a";
        $res = $mysqli->query($sql);
        $num_result = $res->num_rows;


$mysqli->query($sql); 이부분은 쿼리문을 이용해 sql 테이블 a 에 저장된 모든 데이터를 선택하여 쿼리 결과를 생성시킵니다. 

$res->num_rows; num_result에는 db결과가 몇개인지에 대한 정보가 들어갑니다.



<table border='1' align="center">
        <thead>
            <tr>
                <th width="50">NUM</th>
                <th width="250">FILE</th>
                <th width="200">TIME</th>
                <th width="50">id</th>
                <th width="70">subject</th>
                <th width="250">memo</th>
                <th width="70">DOWN</th>
                <th width="50">DEL</th>
                
 
            </tr>
        </thead>
        <tbody>


표의 굵기를 1(border='1')로 하여 가운데 정렬(align="center")하여 표를 만듭니다.

<th>내용</th>는 tale head의 약자로, 표의 제목을 쓰는역할입니다. (기본값 : 굵은글씨, 중앙정렬)

<tr>내용</tr>은 table row의 약자로, 가로줄을 만듭니다. (기본값 : 보통글씨, 왼쪽정렬)

<td>내용</td>는 table data의 약자로, 셀을 만드는 역할입니다. (기본값 : 보통글씨, 왼쪽정렬)


<tr>

<th>이름</th>

<th>나이</th>

</tr>

<tr>

<td>김영수</td>

<td>24</td>

</tr>


일경우


이름

나이

김영수

24

이렇게 된다는 말이죠 !



<?php
                for($i=0; $i<$num_result; $i++)
                {
                    $row = $res->fetch_assoc();
                    echo "<tr>";
                    echo "<td align='center'>".$row['num']."</td>";
                    echo "<td align='left'>
                <a href='./download.php?num=".$row['num']."'>".$row['name']."</a></td>";
                    echo "<td align='center'>".$row['time']."</td>";
                    echo "<td align='center'>".$row['id']."</td>";
                    echo "<td align='center'>
                <a href='./view.php?num=".$row['num']."'>".$row['subject']."</a></td>";    
                    echo "<td align='center'>".$row['memo']."</td>";
                    echo "<td align='center'>".$row['down']."</td>";    
                    echo "<td align='center'>
                <a href='./delete.php?num=".$row['num']."'>DEL</a></td>";                    
                    echo "</tr>";
                }
              mysqli_close($mysqli);
 
              
            ?>


for문을 이용해 총 num_result의 갯수($res->num_rows; num_result에는 db결과가 몇개인지에 대한 정보가 들어갑니다.) 만큼 테이블을 동적으로 생성하게 됩니다.

 $row = $res->fetch_assoc();

각 반복문이 돌아갈때마다 row변수에 select로 뽑아온 데이터가 배열로 저장됩니다.


echo "<td align='center'>".$row['num']."</td>"; 

row변수의 num에 저장되어있는 것이 입력 되겠죠


echo "<td align='left'>

<a href='./download.php?num=".$row['num']."'>".$row['name']."</a></td>";

파일의 name에 하이퍼 링크를 걸어(클릭시 download.php로 이동시키도록)줍니다.


mysqli_close($mysqli);

그리고 sql을 종료시켜줍니다.

결과입니다.




반응형

+ Recent posts