博客列表 >PHP文件上传

PHP文件上传

longlong
longlong原创
2020年08月03日 10:57:16609浏览

1. 单文件上传

  1. <?php
  2. // 可以将判断的信息异常捕获放入try...catch...模块中
  3. echo '<pre>'.print_r($_FILES,true).'</pre>';
  4. // 1. 自定义上传异常类(继承系统的Exception)
  5. class UploadException extends Exception
  6. {
  7. public function __toString()
  8. {
  9. // 将捕获的异常信息放入表格中
  10. return <<< ERROR
  11. <table>
  12. <tr>
  13. <td>异常编号</td>
  14. <td>异常信息</td>
  15. <td>异常文件</td>
  16. <td>异常行数</td>
  17. </tr>
  18. <tr>
  19. <td>$this->code</td>
  20. <td>$this->message</td>
  21. <td>$this->file</td>
  22. <td>$this->line</td>
  23. </tr>
  24. </table>
  25. <style>
  26. table{border-collapse: collapse;border: 1px solid black;text-align: center;}
  27. td{padding: 8px;border: 1px solid black;}
  28. tr:first-of-type{background-color: gray;color: white;}
  29. tr:last-of-type{color: red;}
  30. </style>
  31. ERROR;
  32. }
  33. }
  34. try {
  35. // 2. 判断错误代码值,抛出相应的异常信息
  36. $errorCode = $_FILES['file_name']['error'] ?? null;
  37. if ($errorCode > UPLOAD_ERR_OK) {
  38. switch ($errorCode) {
  39. case UPLOAD_ERR_INI_SIZE :
  40. throw new UploadException('文件超过`php.ini`中`upload_max_filesize`值',1);
  41. break;
  42. case UPLOAD_ERR_FORM_SIZE :
  43. throw new UploadException('文件大小超过表单中`MAX_FILE_SIZE`指定的值',2);
  44. break;
  45. case UPLOAD_ERR_PARTIAL :
  46. throw new UploadException('文件只有部分被上传',3);
  47. break;
  48. case UPLOAD_ERR_NO_FILE :
  49. throw new UploadException('没有文件被上传',4);
  50. break;
  51. case UPLOAD_ERR_NO_TMP_DIR :
  52. throw new UploadException('找不到临时文件夹',6);
  53. break;
  54. default:
  55. throw new UploadException("未知错误,上传失败", 7);
  56. }
  57. }
  58. // 3. 判断临时文件上传方式是否正确,抛出相应异常信息
  59. $tempFileName = $_FILES['file_name']['tmp_name'] ?? null;
  60. // 如果不是POST方式上传,抛出异常
  61. if($_POST['btn'] === 1){
  62. if (!($tempFileName && is_uploaded_file($tempFileName))){
  63. throw new UploadException('上传方式有误',8);
  64. }
  65. }
  66. // 如果上传方式正确,将临时文件储存到uploads目录下
  67. if ($tempFileName && is_uploaded_file($tempFileName)){
  68. $originalFileName = $_FILES['file_name']['name'] ?? null;
  69. $destination = 'uploads/'.md5(time()).mt_rand(1,10000).strstr($originalFileName,".");
  70. if(move_uploaded_file($tempFileName,$destination)){
  71. echo "<br>临时文件储存在: ".$tempFileName;
  72. echo "<br>现在文件被移动到: ".$destination;
  73. echo "<br>文件上传成功";
  74. echo "<br><img src='{$destination}' width='180'>";
  75. }
  76. }
  77. // 4. 判断文件类型是否正确,抛出相应异常信息
  78. $fileType = $_FILES['file_name']['type'] ?? null;
  79. $endType = strstr($fileType,"/",true);
  80. if (!is_null($fileType)){
  81. if($endType !== "image")
  82. throw new UploadException('上传文件格式错误,请上传image类型的图片',9);
  83. }
  84. } catch (UploadException $e) {
  85. echo $e;
  86. }
  87. ?>
  88. <!DOCTYPE html>
  89. <html lang="en">
  90. <head>
  91. <meta charset="UTF-8" />
  92. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  93. <title>文件上传异常处理</title>
  94. </head>
  95. <body>
  96. <form action="" method="POST" enctype="multipart/form-data">
  97. <fieldset>
  98. <legend>单文件上传</legend>
  99. <!-- 设置前端上传文件的大小 -->
  100. <input type="hidden" name="MAX_FILE_SIZE" value="380000">
  101. <input type="file" name="file_name" />
  102. <button name="btn" value="1">上传</button>
  103. </fieldset>
  104. </form>
  105. </body>
  106. </html>

2. 多文件上传方式一:使用多个<input>

  1. <?php
  2. error_reporting(E_ALL);
  3. echo '<pre>'.print_r($_FILES,true).'</pre>';
  4. // 1. 自定义异常
  5. class UploadException extends Exception
  6. {
  7. public function __toString()
  8. {
  9. // 将捕获的异常信息放入表格中
  10. return <<< ERROR
  11. <table>
  12. <tr>
  13. <td>异常编号</td>
  14. <td>异常信息</td>
  15. <td>异常文件</td>
  16. <td>异常行数</td>
  17. </tr>
  18. <tr>
  19. <td>$this->code</td>
  20. <td>$this->message</td>
  21. <td>$this->file</td>
  22. <td>$this->line</td>
  23. </tr>
  24. </table>
  25. <style>
  26. table{border-collapse: collapse;border: 1px solid black;text-align: center;}
  27. td{padding: 8px;border: 1px solid black;}
  28. tr:first-of-type{background-color: gray;color: white;}
  29. tr:last-of-type{color: red;}
  30. </style>
  31. ERROR;
  32. }
  33. }
  34. try {
  35. // 多文件上传时,先遍历$_FILES
  36. foreach($_FILES as $file){
  37. // 2. 判断错误代码值,抛出相应的异常信息
  38. $errorCode = $file['error'] ?? null;
  39. if ($errorCode > UPLOAD_ERR_OK) {
  40. switch ($errorCode) {
  41. case UPLOAD_ERR_INI_SIZE :
  42. throw new UploadException('文件超过`php.ini`中`upload_max_filesize`值',1);
  43. break;
  44. case UPLOAD_ERR_FORM_SIZE :
  45. throw new UploadException('文件大小超过表单中`MAX_FILE_SIZE`指定的值',2);
  46. break;
  47. case UPLOAD_ERR_PARTIAL :
  48. throw new UploadException('文件只有部分被上传',3);
  49. break;
  50. case UPLOAD_ERR_NO_FILE :
  51. throw new UploadException('没有文件被上传',4);
  52. break;
  53. case UPLOAD_ERR_NO_TMP_DIR :
  54. throw new UploadException('找不到临时文件夹',6);
  55. break;
  56. default:
  57. throw new UploadException("未知错误,上传失败", 7);
  58. }
  59. }
  60. // 3. 判断临时文件上传方式是否正确,抛出相应异常信息
  61. $tmpFileName = $file['tmp_name'] ?? null;
  62. // 如果不是POST方式上传,抛出异常
  63. if($_POST['btn'] === 1){
  64. if (!($tmpFileName && is_uploaded_file($tmpFileName))){
  65. throw new UploadException('上传方式有误',8);
  66. }
  67. }
  68. // 如果上传方式正确,将临时文件储存到uploads目录下
  69. if ($tmpFileName && is_uploaded_file($tmpFileName)){
  70. $originalFileName = $file['name'] ?? null;
  71. $destination = 'uploads/'.md5(time()).mt_rand(1,10000).strstr($originalFileName,".");
  72. if(move_uploaded_file($tmpFileName,$destination)){
  73. echo "<img src='{$destination}' width='180'>";
  74. echo "<span style='color:red;font-size:1.5rem;'>{$originalFileName} 上传成功 </span><hr>";
  75. }
  76. }
  77. // 4. 判断文件类型是否正确,抛出相应异常信息
  78. $fileType = $file['type'] ?? null;
  79. $endType = strstr($fileType,"/",true);
  80. if (!is_null($fileType)){
  81. if($endType !== "image")
  82. throw new UploadException('上传文件格式错误,请上传image类型的图片',9);
  83. }
  84. }
  85. } catch (UploadException $e) {
  86. echo $e;
  87. }
  88. ?>
  89. <!DOCTYPE html>
  90. <html lang="en">
  91. <head>
  92. <meta charset="UTF-8">
  93. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  94. <title>多文件上传</title>
  95. </head>
  96. <body>
  97. <form action="" method="POST" enctype="multipart/form-data">
  98. <fieldset>
  99. <legend>批量上传文件</legend>
  100. <!-- 隐藏域设置上传文件大小,必须写到input:file之前 -->
  101. <!-- <input type="hidden" name="MAX_FILE_SIZE" value="55000"> -->
  102. <input type="file" name="file1" > <br>
  103. <input type="file" name="file2" > <br>
  104. <input type="file" name="file3" >
  105. <button name="btn" value="1">上传</button>
  106. </fieldset>
  107. </form>
  108. </body>
  109. </html>

3. 多文件上传方式二:只有一个<input>

  • upload.php:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>多文件上传批量处理</title>
  7. </head>
  8. <body>
  9. <form action="check.php" method="POST" enctype="multipart/form-data">
  10. <fieldset>
  11. <legend>多文件上传</legend>
  12. <!-- 设置前端上传文件的大小 -->
  13. <!-- <input type="hidden" name="MAX_FILE_SIZE" value="380000"> -->
  14. <input type="file" name="file[]" multiple />
  15. <button name="btn" value="1">上传</button>
  16. </fieldset>
  17. </form>
  18. </body>
  19. </html>
  • check.php:
  1. <?php
  2. // 可以将判断的信息异常捕获放入try...catch...模块中
  3. // 测试数据显示的代码,根据测试才有了以下的写法
  4. // echo '<pre>'.print_r($_FILES['file'],true).'</pre>';
  5. // print_r($_FILES['file']['name']);
  6. // print_r($_FILES['file']['type']);
  7. // print_r($names)
  8. // echo $names[0];
  9. // print_r( $types);
  10. // 将三维数组全部转为一维数组,将$_FILES的键值直接保存下来,后期直接遍历相应的数组就可以取出值来
  11. $names = $_FILES['file']['name'];
  12. $types = $_FILES['file']['type'];
  13. $tmp_names = $_FILES['file']['tmp_name'];
  14. $errors = $_FILES['file']['error'];
  15. $sizes = $_FILES['file']['size'];
  16. // 1. 自定义上传异常类(继承系统的Exception)
  17. class UploadException extends Exception
  18. {
  19. public function __toString()
  20. {
  21. // 将捕获的异常信息放入表格中
  22. return <<< ERROR
  23. <table>
  24. <tr>
  25. <td>异常编号</td>
  26. <td>异常信息</td>
  27. <td>异常文件</td>
  28. <td>异常行数</td>
  29. </tr>
  30. <tr>
  31. <td>$this->code</td>
  32. <td>$this->message</td>
  33. <td>$this->file</td>
  34. <td>$this->line</td>
  35. </tr>
  36. </table>
  37. <style>
  38. table{border-collapse: collapse;border: 1px solid black;text-align: center;}
  39. td{padding: 8px;border: 1px solid black;}
  40. tr:first-of-type{background-color: gray;color: white;}
  41. tr:last-of-type{color: red;}
  42. </style>
  43. ERROR;
  44. }
  45. }
  46. try {
  47. // 2. 判断错误代码值,抛出相应的异常信息
  48. foreach($errors as $errorCode){
  49. if ($errorCode > UPLOAD_ERR_OK) {
  50. switch ($errorCode) {
  51. case UPLOAD_ERR_INI_SIZE :
  52. throw new UploadException('文件超过`php.ini`中`upload_max_filesize`值',1);
  53. break;
  54. case UPLOAD_ERR_FORM_SIZE :
  55. throw new UploadException('文件大小超过表单中`MAX_FILE_SIZE`指定的值',2);
  56. break;
  57. case UPLOAD_ERR_PARTIAL :
  58. throw new UploadException('文件只有部分被上传',3);
  59. break;
  60. case UPLOAD_ERR_NO_FILE :
  61. throw new UploadException('没有文件被上传',4);
  62. break;
  63. case UPLOAD_ERR_NO_TMP_DIR :
  64. throw new UploadException('找不到临时文件夹',6);
  65. break;
  66. default:
  67. throw new UploadException("未知错误,上传失败", 7);
  68. }
  69. }
  70. }
  71. // 3. 判断临时文件上传方式是否正确,抛出相应异常信息
  72. foreach($tmp_names as $index => $tmpFileName){
  73. // 如果不是POST方式上传,抛出异常
  74. if($_POST['btn'] === 1){
  75. if (!($tmpFileName && is_uploaded_file($tmpFileName))){
  76. throw new UploadException('上传方式有误',8);
  77. }
  78. }
  79. // 如果上传方式正确,将临时文件储存到uploads目录下
  80. // 上面遍历的临时文件名中$index的作用就在这里,根据$tmp_names[$index]就可以取到$names[$index]
  81. // 因为它们的键名都是相对应的,所以可以通过$index拿到文件名的后缀
  82. if ($tmpFileName && is_uploaded_file($tmpFileName)){
  83. $destination = 'uploads/'.md5(time()).mt_rand(1,10000).strstr($names[$index],".");
  84. if(move_uploaded_file($tmpFileName,$destination)){
  85. echo "<img src='{$destination}' width='180'>";
  86. echo "<span style='color:red;font-size:1.5rem;'> {$names[$index]}上传成功 </span><hr>";
  87. }
  88. }
  89. }
  90. // 4. 判断文件类型是否正确,抛出相应异常信息
  91. foreach($types as $filetype){
  92. $endType = strstr($fileType,"/",true);
  93. if (!is_null($fileType)){
  94. if($endType !== "image")
  95. throw new UploadException('上传文件格式错误,请上传image类型的图片',9);
  96. }
  97. }
  98. } catch (UploadException $e) {
  99. echo $e;
  100. }
  101. ?>

4. 封装一个类,支持单元件与多文件上传

  • index.php:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>多文件上传批量处理</title>
  7. </head>
  8. <body>
  9. <form action="check.php" method="POST" enctype="multipart/form-data">
  10. <fieldset>
  11. <legend>多文件上传</legend>
  12. <!-- 设置前端上传文件的大小 -->
  13. <!-- <input type="hidden" name="MAX_FILE_SIZE" value="380000"> -->
  14. <input type="file" name="file[]" multiple />
  15. <button name="btn" value="1">上传</button>
  16. </fieldset>
  17. </form>
  18. </body>
  19. </html>
  • UploadFile.php:
  1. <?php
  2. // 1. 自定义上传异常类(继承系统的Exception)
  3. class UploadException extends Exception
  4. {
  5. public function __toString()
  6. {
  7. // 将捕获的异常信息放入表格中
  8. return <<< ERROR
  9. <table>
  10. <tr>
  11. <td>异常编号</td>
  12. <td>异常信息</td>
  13. <td>异常文件</td>
  14. <td>异常行数</td>
  15. </tr>
  16. <tr>
  17. <td>$this->code</td>
  18. <td>$this->message</td>
  19. <td>$this->file</td>
  20. <td>$this->line</td>
  21. </tr>
  22. </table>
  23. <style>
  24. table{border-collapse: collapse;border: 1px solid black;text-align: center;}
  25. td{padding: 8px;border: 1px solid black;}
  26. tr:first-of-type{background-color: gray;color: white;}
  27. tr:last-of-type{color: red;}
  28. </style>
  29. ERROR;
  30. }
  31. }
  32. class UploadFile extends UploadException
  33. {
  34. public $names;
  35. public $types;
  36. public $tmp_names;
  37. public $errors;
  38. public $sizes;
  39. public function __construct($types,$tmp_names,$errors,$names,$sizes)
  40. {
  41. $this->names = $names;
  42. $this->types = $types;
  43. $this->tmp_names = $tmp_names;
  44. $this->errors = $errors;
  45. $this->sizes = $sizes;
  46. return $this->check();
  47. }
  48. public function check (){
  49. try {
  50. // 2. 判断错误代码值,抛出相应的异常信息
  51. foreach($this->errors as $errorCode){
  52. if ($errorCode > UPLOAD_ERR_OK) {
  53. switch ($errorCode) {
  54. case UPLOAD_ERR_INI_SIZE :
  55. throw new UploadException('文件超过`php.ini`中`upload_max_filesize`值',1);
  56. break;
  57. case UPLOAD_ERR_FORM_SIZE :
  58. throw new UploadException('文件大小超过表单中`MAX_FILE_SIZE`指定的值',2);
  59. break;
  60. case UPLOAD_ERR_PARTIAL :
  61. throw new UploadException('文件只有部分被上传',3);
  62. break;
  63. case UPLOAD_ERR_NO_FILE :
  64. throw new UploadException('没有文件被上传',4);
  65. break;
  66. case UPLOAD_ERR_NO_TMP_DIR :
  67. throw new UploadException('找不到临时文件夹',6);
  68. break;
  69. default:
  70. throw new UploadException("未知错误,上传失败", 7);
  71. }
  72. }
  73. }
  74. // 3. 判断临时文件上传方式是否正确,抛出相应异常信息
  75. foreach($this->tmp_names as $index => $tmpFileName){
  76. // 如果不是POST方式上传,抛出异常
  77. if($_POST['btn'] === 1){
  78. if (!($tmpFileName && is_uploaded_file($tmpFileName))){
  79. throw new UploadException('上传方式有误',8);
  80. }
  81. }
  82. // 如果上传方式正确,将临时文件储存到uploads目录下
  83. // 上面遍历的临时文件名中$index的作用就在这里,根据$tmp_names[$index]就可以取到$names[$index]
  84. // 因为它们的键名都是相对应的,所以可以通过$index拿到文件名的后缀
  85. if ($tmpFileName && is_uploaded_file($tmpFileName)){
  86. $destination = 'uploads/'.md5(time()).mt_rand(1,10000).strstr($this->names[$index],".");
  87. if(move_uploaded_file($tmpFileName,$destination)){
  88. echo "<img src='{$destination}' width='180'>";
  89. echo "<span style='color:red;font-size:1.5rem;'> {$names[$index]}上传成功 </span><hr>";
  90. }
  91. }
  92. }
  93. // 4. 判断文件类型是否正确,抛出相应异常信息
  94. foreach($this->types as $filetype){
  95. $endType = strstr($fileType,"/",true);
  96. if (!is_null($fileType)){
  97. if($endType !== "image")
  98. throw new UploadException('上传文件格式错误,请上传image类型的图片',9);
  99. }
  100. }
  101. } catch (UploadException $e) {
  102. echo $e;
  103. }
  104. }
  105. }
  106. ?>
  • check.php:
  1. <?php
  2. spl_autoload_register('meth');
  3. function meth ($class){
  4. $file = __DIR__.'/'.$class.'.php';
  5. require_once $file;
  6. }
  7. $types = $_FILES['file']['type'] ?? null;
  8. $tmp_names = $_FILES['file']['tmp_name'] ?? null;
  9. $errors = $_FILES['file']['error'] ?? null;
  10. $sizes = $_FILES['file']['size'] ?? null;
  11. $names = $_FILES['file']['name'] ?? null;
  12. $obj = new UploadFile($types,$tmp_names,$errors,$names,$sizes);
  13. ?>

5. 总结

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议