目前共有7篇帖子。 內容轉換:不轉換▼
 
點擊 回復
389 6
【示例】PHP文件上传
一派護法 十九級
1樓 發表于:2016-6-16 21:31

<!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>
一派護法 十九級
2樓 發表于:2016-6-16 21:33

一派護法 十九級
3樓 發表于:2016-6-16 21:34

一派護法 十九級
4樓 發表于:2016-6-16 21:36

其中最后一个文件由于其大小超过了表单中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浏览器下都能正常工作。
一派護法 十九級
5樓 發表于:2016-6-16 21:37

服务器上保存的上传成功的文件:

一派護法 十九級
6樓 發表于:2016-6-16 21:51

为了安全起见,在服务器端最好检查一下$file['size'],因为MAX_FILE_SIZE很容易在客户端被改掉。MAX_FILE_SIZE应该只用来避免用户等待大文件上传完了之后才发现上传失败的麻烦。
另外$file['type']也是由浏览器提供的,不是很可靠,所以最好用php的finfo类来确定文件的类型。
具体示例:https://zh.arslanbar.net/post.php?t=23829
一派護法 十九級
7樓 發表于:2016-6-17 15:35

PHP官方手册中已明确说明:
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field
意思是说,MAX_FILE_SIZE隐藏域必须放在文件选择框之前。

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:389 回複數:6
評論數: ?
作者: 巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2016-6-17 15:35
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。