Blogger Information
Blog 38
fans 1
comment 0
visits 28660
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
12月09日_PHP文件上传
fkkf467
Original
685 people have browsed it

1. 文件上传

form.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>文件上传</title>
  6. </head>
  7. <body>
  8. <h2>文件上传</h2>
  9. <!--文件上传必须是post类型-->
  10. <form action="upload_file.php" method="post" enctype="multipart/form-data">
  11. <!-- name 一定要有,因为name最终会成为php中的$_FILES['my_file']-->
  12. <input type="file" name="my_file">
  13. <button>上传</button>
  14. </form>
  15. </body>
  16. </html>

upload_file.php

  1. <?php
  2. // 文件上传
  3. // 1. 配置上传参数
  4. // 允许上传的文件类型
  5. $fileType = ['jpg', 'png', 'gif'];
  6. // 允许上传的文件大小,限制为3M
  7. $fileSize = 3145728;
  8. // 文件上传的路径
  9. $filePath = '/uploads/';
  10. // 原始文件名
  11. $fileName = $_FILES['my_file']['name'];
  12. // 临时文件名
  13. $tempFile = $_FILES['my_file']['tmp_name'];
  14. // 2. 判断是否上传成功
  15. $uploadError = $_FILES['my_file']['error'];
  16. if ($uploadError > 0) {
  17. switch ($uploadError) {
  18. case 1:
  19. case 2:
  20. die('上传文件不能超过3M');
  21. case 3:
  22. die('上传文件不完整');
  23. case 4:
  24. die('没有选择文件');
  25. default:
  26. die('未知错误');
  27. }
  28. }
  29. // 3. 判断文件扩展名是否正确
  30. $extension = explode('.', $fileName)[1];
  31. if (!in_array($extension, $fileType)) {
  32. die('不允许上传' . $extension . '类型的文件');
  33. }
  34. // 4. 将上传后的文件重命名,防止同名文件覆盖
  35. $fileName = date('YmdHis', time()) . md5(mt_rand(1, 99)) . '.' . $extension;
  36. // 5. 上传文件
  37. // 判断是否是通过POST传值
  38. if (is_uploaded_file($tempFile)) {
  39. if (move_uploaded_file($tempFile, __DIR__ . $filePath . $fileName)) {
  40. echo '<script>alert("上传成功");history.back();</script>';
  41. } else {
  42. die('上传失败');
  43. }
  44. } else {
  45. die('非法操作');
  46. }
  47. exit();



2. 总结

学会了文件上传操作的相关过程。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:文件上传看上去很简单, 其实里面还是有许多细节的, 值得研究
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments