Simple PHP file uploader

Takes advantage of HTML 5 multiple file select.
Very crude security mechanism.

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
<?php
 
function upload() {
  $input_name = 'userfile';
  $upload_key = 'key goes here';
  $upload_dir = './';
  $accepted_mime_types = array(
    'image/png',
    'image/gif',
    'image/jpeg'
  );
 
  if (isset($_FILES[$input_name]) && count($_FILES[$input_name][name]) > 0) {
    echo '<p>';
    if ($_POST['key'] != $upload_key) {
      echo 'Invalid key';
    }
    else {
      for ($i = 0; $i < count($_FILES[$input_name][name]); $i++) {
        $result = '';
        if ($_FILES[$input_name]['error'][$i] != UPLOAD_ERR_OK) {
          $result = 'Upload failed with error';
        }
        else {
          $upload_file = $upload_dir . basename($_FILES[$input_name]['name'][$i]);
          if (!in_array($_FILES[$input_name]['type'][$i], $accepted_mime_types)) {
            $result = 'Invalid mime type - ' . $_FILES[$input_name]['type'][$i];
          }
          else if (file_exists($upload_file)) {
            $result = 'File already exists';
          }
          else if (!move_uploaded_file($_FILES[$input_name]['tmp_name'][$i], $upload_file)) {
            $result = 'Move failed';
          }
          else {
            $result = 'Upload succeeded - <a href="' . $upload_file . '">' . basename($upload_file) . '</a>';
          }
        }
        echo '<b>' . basename($_FILES[$input_name]['name'][$i]) . ':</b> ' . $result . '<br />';
      }
    }
    echo '</p>';
  }
}
 
?>
<html>
<body>
<?php upload(); ?>
<p>Formats: PNG, GIF, JPEG</p>
<p>Max file size: 256KB</p>
<form enctype="multipart/form-data" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="262144" />
    <label for="key">Key</label>
    <input type="text" id="key" name="key" />
    <label for="file">File</label>
    <input name="userfile[]" id="userfile[]" type="file" multiple />
    <input type="submit" value="Upload Image(s)" />
</form>
</body>
</html>