|
【示例】PHP文件上傳 |
一派掌門 二十級 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Files</title> <style> table { border-collapse: collapse; } </style> </head>
<body> <p>Count: <?php echo count($_FILES); ?></p> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'): ?> <table width="100%" border="1" cellpadding="1" cellspacing="0"> <tbody> <tr bgcolor="#EEEEEE"> <th width="20%" scope="col">Name</th> <th width="20%" scope="col">Type</th> <th width="20%" scope="col">Size</th> <th width="20%" scope="col">Temp Name</th> <th scope="col">Error</th> </tr> <?php foreach ($_FILES as $name => &$file): $filename = sprintf('storage/%s.dat', $name); move_uploaded_file($file['tmp_name'], $filename); ?> <tr> <td width="20%" align="center"><?php echo $file['name']; ?></td> <td width="20%" align="center"><?php echo $file['type']; ?></td> <td width="20%" align="center"><?php echo $file['size']; ?></td> <td width="20%" align="center"><?php echo $file['tmp_name']; ?></td> <td align="center"><?php echo $file['error']; ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <form method="post" enctype="multipart/form-data" name="form1" id="form1"> <!-- 限制文件大小的隱藏域必須在文件選擇框前面, 否則無效 --> <input name="MAX_FILE_SIZE" type="hidden" id="MAX_FILE_SIZE" value="2000"> <p> <label for="file1">File:</label> <input type="file" name="file1" id="file1"> <br> <label for="file2">File:</label> <input type="file" name="file2" id="file2"> <br> <label for="file3">File:</label> <input type="file" name="file3" id="file3"> </p> <p> <input type="submit" value="Submit"> </p> </form> <?php endif; ?> </body> </html>
|
一派掌門 二十級 |
|
|
一派掌門 二十級 |
|
|
一派掌門 二十級 |
其中最後一個文件由於其大小超過了表單中MAX_FILE_SIZE隱藏域中指定的最大值:2000位元組,所以上傳失敗,錯誤碼為2:
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE
directive that was specified in the HTML form.
(錯誤碼列表請參閱: http://php.net/manual/en/features.file-upload.errors.php) 經測試,MAX_FILE_SIZE的文件大小檢查功能在IE、Firefox、Opera瀏覽器下都能正常工作。
|
|
一派掌門 二十級 |
伺服器上保存的上傳成功的文件:
|
|
一派掌門 二十級 |
為了安全起見,在伺服器端最好檢查一下$file['size'],因為MAX_FILE_SIZE很容易在客戶端被改掉。MAX_FILE_SIZE應該只用來避免用戶等待大文件上傳完了之後才發現上傳失敗的麻煩。 另外$file['type']也是由瀏覽器提供的,不是很可靠,所以最好用php的finfo類來確定文件的類型。 具體示例: https://zh.arslanbar.net/post.php?t=23829
|
|
一派掌門 二十級 |
PHP官方手冊中已明確說明: The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field 意思是說,MAX_FILE_SIZE隱藏域必須放在文件選擇框之前。
|
|