ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [PHP] 27. 파일 업로드(File Upload) - PHP 강좌, PHP5
    Web/PHP 2015. 6. 13. 13:55

    PHP 5 File Upload
     PHP에서, 서버에 파일을 업로드 하는 것은 쉬운 일입니다.
     



    1. Configure The "php.ini" File
     첫째로, 파일을 업로드하는 것을 허용하기를 수정해야 합니다.

     자신의 php.ini 파일에서 아래와 같이 수정해줍니다.


    1
    file_uploads = On
    cs






    2. Create The HTML Form
     다음으로, 업로드하길 원하는 이미지 파일을 사용자가 선택할 수 있는 HTML 서식을 생성합니다:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html>
    <body>
     
    <form action="upload.php" method="post" enctype="multipart/form-data">
        Select image to upload:
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload Image" name="submit">
    </form>
     
    </body>
    </html>
    cs

     



     위 HTML 서식에서 몇 가지 규칙을 따릅니다:
      - 서식은 메소드 "post" 방식을 사용하기를 확정해야 합니다.
      - 서식은 또한 attribute: enctype을 "multipart/form-data"로 따라야합니다.

     위 조건을 따르지 않는다면, 파일 업로드는 작동하지 않습니다.

     


    3. Create The Upload File PHP Script
     upload.php 파일은 파일 업로드를 위한 코드를 포함해야 합니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    ?>
    cs












     PHP 스크립트 설명:
     - $target_dir = "uploads/" : 파일이 위치할 디렉토리를 명시합니다.
     - $target_file : 파일이 업로드 될 경로를 명시합니다.
     - $uploadOk = 1 : 아직 사용되지 않습니다(나중에 사용 할 것 입니다.)
     - $imageFileType : 파일의 확장자를 갖습니다.
     - 사진이 실제 사진인지 가짜 사진인지 체크합니다.

     * 노트: upload.php 파일이 있는 곳에 uploads 라는 디렉토리를 생성해야 할 것 입니다. 업로드된 파일이 그 곳에 저장될 것 입니다. 





    4. Check if File Already Exists
     이제 몇 가지 제한사항을 추가 할 것 입니다.

     첫째로, uploads 폴더에 파일이 이미 존재하는지 체크할 것 입니다. 만약 존재한다면, 에러 메세지를 출력할 것이고, $uploadOK는 0으로 설정 될 것 입니다.


    1
    2
    3
    4
    5
    6
    7
    <?php
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    ?>
    cs







    5. Limit File Size
     HTML 서식의 파일 입력 필드는 fileToUpload라는 이름으로 되어 있습니다.

     파일의 사이즈를 체크하는 것을 작성하겠습니다. 파일이 500kb를 넘는다면, 에러 메세지를 출력하고, $uploadOk는 0으로 설정 될 것 입니다.



    1
    2
    3
    4
    5
    6
    7
    <?php
     // Check file size
    if ($_FILES["fileToUpload"]["size"> 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    ?>
    cs
     





    6. Limit File Type
     아래 코드는 사용자가 JPG, JPEG, PNG, GIF 파일만을 업로드 하기를 허용하는 코드입니다. 

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <?php
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
     
    ?>
    cs
     






    7. Complete Upload File PHP Script
     완성된 upload.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
    <!DOCTYPE html>
    <html>
     
    <body>
     
    <form action="upload.php" method="post" enctype="multipart/form-data">
        Select image to upload:
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload Image" name="submit">
    </form>
     
    <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"> 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file "basename$_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>
    </body>
    </html>
    cs

     


     






    댓글

Designed by Tistory.