2018년 5월 22일 화요일

[PHP예제] 230 여러장의 이미지 업로드하기




  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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>여러장의 이미지 업로드하기</title>
</head>
<body>
<div>
<?php
require_once './h.php';

$dir = './upload';
const MAX_SIZE = 102400;

// 'php.ini'의 post_max_size를 넘은 데이터가 전송되었는지 확인함
if( !checkPostMaxSize() )
{
  echo "파일 크기는 100KB 이하로 하시오.<br><br>";
}

// 파일이 업로드 되었는지 확인
if( isset($_FILES['uploadfile']) )
{
  // 반복 처리
  for( $i = 0; $i < count($_FILES['uploadfile']['name']); $i++ )
  {
    // 업로드 파일을 확인함
    list($result, $ext, $error_msg) = checkFile($i);
    if( $result )
    {
      $name = $_FILES['uploadfile']['name'][$i];
      $tmp_name = $_FILES['uploadfile']['tmp_name'][$i];

      // 여기에서는 저장할 디렉터리의 아래쪽에 '"upfile_" + 현재의 타임스탬프
      // + 일련번호 + "_"
      // + 마이크로초와 전체 파일명, 연결 전 IP 주소에 근거하는 MD5
      // + 확장자'로 배치함
      $move_to = $dir . '/upfile_' . time() . $i . '_'
                  . md5(microtime() . $name . $_SERVER['REMOTE_ADDR'])
                  . '.' . $ext;

      // 업로드한 임시 파일을 지정한 장소로 이동함
      if( move_uploaded_file($tmp_name, $move_to) )
      {
        // 이미지 파일을 표시함
        echo h($move_to) . '<br>';
        echo '<img src="' . h($move_to) . '" alt="업로드된 이미지"><br>';
      }
      else
      {
        $error_msg[] = '이미지의 업로드 실패';
      }
    }

    // 오류 메시지가 있으면 표시
    if( count($error_msg) > 0 )
    {
      foreach( $error_msg as $msg )
      {
        echo h($msg) . "<br>";
      }
    }
  }
}

function checkFile($i)  // 업로드 파일을 확인하는 함수
{
  $error_msg = array();
  $ext = '';

  $size = $_FILES['uploadfile']['size'][$i];
  $error = $_FILES['uploadfile']['error'][$i];
  $img_type = $_FILES['uploadfile']['type'][$i];
  $tmp_name = $_FILES['uploadfile']['tmp_name'][$i];

  if( $error != UPLOAD_ERR_OK ) // 업로드 오류의 경우
  {
    if( $error == UPLOAD_ERR_NO_FILE )
    {
      // 업로드되지 않은 경우는 오류 처리를 하지 않음
    }
    elseif( $error == UPLOAD_ERR_INI_SIZE
          || $error == UPLOAD_ERR_FORM_SIZE )
    {
      // 파일 크기 오류
      $error_msg[] = '파일 크기는 100KB 이하로 하시오.';
    }
    else
    {
      $error_msg[] = '업로드 오류임';
    }

    return array(false, $ext, $error_msg);
  }
  else
  {
    // 전송된 MIME 타입으로부터 확장자를 결정함
    if( $img_type == 'image/gif' )
    {
      $ext = 'gif';
    }
    elseif( $img_type == 'image/jpeg' || $img_type == 'image/pjpeg' )
    {
      $ext = 'jpg';
    }
    elseif( $img_type == 'image/png' || $img_type == 'image/x-png' )
    {
      $ext = 'png';
    }

    // 이미지 파일의 MIME 타입을 판별
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $finfoType = $finfo->file($tmp_name);

    // 이미지 파일의 크기의 하한을 확인함
    if( $size == 0 )
    {
      $error_msg[] = '파일이 존재하지 않거나 빈 파일임';
    }
    elseif( $size > MAX_SIZE )
    {
      $error_msg[] = '파일 크기는 100KB 이하로 하시오.';
    }
    elseif( $img_type != $finfoType )
    {
      $error_msg[] = 'MIME 타입이 일치하지 않음';
    }
    elseif( $ext != 'gif' && $ext != 'jpg' && $ext != 'png' )
    {
      $error_msg[] = '업로드 가능 파일은 gif, jpg, png 임';
    }
    else
    {
      return array(true, $ext, $error_msg);
    }
  }

  return array(false, $ext, $error_msg);
}

// 'php.ini'의 post_max_size를 넘은 데이터가 전송되었는지를 확인하는 함수
function checkPostMaxSize()
{
  $max_size = ini_get('post_max_size');

  // post_max_size가 8MB와 같이 설정된 경우에 정수로 함
  $multiple = 1;
  $unit = substr($max_size, -1);
  if( $unit == 'M' )
  {
    $multiple = 1024 * 1024;
  }
  elseif( $unit == 'K' )
  {
    $multiple = 1024;
  }
  elseif( $unit == 'G' )
  {
    $multiple = 1024 * 1024 * 1024;
  }
  $max_size = substr($max_size, 0, strlen($max_size) - 1) * $multiple;

  // post_max_size를 넘어선 데이터가 게시되었는지 확인
  if( $_SERVER['REQUEST_METHOD'] == 'POST' &&
      $_SERVER['CONTENT_LENGTH'] > $max_size )
  {
    return false;
  }
  else
  {
    return true;
  }
}
?>
  <hr>
  <p>업로드하고 싶은 이미지 파일(gif, jpg, png)을 지정하시오</p>
  <form method="post" action="230.php" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo h(MAX_SIZE); ?>">
    <input type="file" name="uploadfile[]"><br>
    <input type="file" name="uploadfile[]"><br>
    <input type="file" name="uploadfile[]"><br>
    <input type="submit" value="전송"><br>
    이미지 사이즈는 1개의 이미지에 대해 100KB 이하
  </form>
</div>
</body>
</html>




댓글 없음:

댓글 쓰기