当前位置:  首页>> 技术小册>> PHP合辑2-高级进阶

您是否曾经想知道PHP是如何构建文件上传系统的?在这里,我们将了解文件上传过程。您可能会问:“我们能否使用此系统上传任何类型的文件?”。答案是肯定的,我们可以上传不同扩展名的文件。

方法:要运行PHP脚本,我们需要服务器。因此,请确保在您的Windows计算机上安装了XAMPP服务器或WAMP服务器。

HTML代码片段:以下是将文件上传到服务器所需的HTML表单的HTML源代码。在HTML的<form>标签中,我们使用“enctype=’multipart/form-data’”,这是一种允许通过POST方法发送文件的编码类型。没有这种编码,文件无法通过POST方法发送。如果您希望允许用户通过表单上传文件,则必须使用此enctype。

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>File Upload Form</title>
  6. </head>
  7. <body>
  8. <form action="file-upload-manager.php" method="post" enctype="multipart/form-data">
  9. <!--multipart/form-data ensures that form data is going to be encoded as MIME data-->
  10. <h2>Upload File</h2>
  11. <label for="fileSelect">Filename:</label>
  12. <input type="file" name="photo" id="fileSelect">
  13. <input type="submit" name="submit" value="Upload">
  14. <!-- name of the input fields are going to be used in our php script-->
  15. <p><strong>Note:</strong>Only .jpg, .jpeg, .png formats allowed to a max size of 2MB.</p>
  16. </form>
  17. </body>
  18. </html>

现在,我们来编写一个能够处理文件上传系统的PHP脚本。 file-upload-manager.php

  1. <?php
  2. // Check if the form was submitted
  3. if($_SERVER["REQUEST_METHOD"] == "POST")
  4. {
  5. // Check if file was uploaded without errors
  6. if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)
  7. {
  8. $allowed_ext = array("jpg" => "image/jpg",
  9. "jpeg" => "image/jpeg",
  10. "gif" => "image/gif",
  11. "png" => "image/png");
  12. $file_name = $_FILES["photo"]["name"];
  13. $file_type = $_FILES["photo"]["type"];
  14. $file_size = $_FILES["photo"]["size"];
  15. // Verify file extension
  16. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  17. if (!array_key_exists($ext, $allowed_ext))
  18. die("Error: Please select a valid file format.");
  19. // Verify file size - 2MB max
  20. $maxsize = 2 * 1024 * 1024;
  21. if ($file_size > $maxsize)
  22. die("Error: File size is larger than the allowed limit of 2MB");
  23. // Verify MYME type of the file
  24. if (in_array($file_type, $allowed_ext))
  25. {
  26. // Check whether file exists before uploading it
  27. if (file_exists("upload/".$_FILES["photo"]["name"]))
  28. echo $_FILES["photo"]["name"]." already exists!";
  29. else
  30. {
  31. move_uploaded_file($_FILES["photo"]["tmp_name"],
  32. "uploads/".$_FILES["photo"]["name"]);
  33. echo "Your file uploaded successfully.";
  34. }
  35. }
  36. else
  37. {
  38. echo "Error: Please try again!";
  39. }
  40. }
  41. else
  42. {
  43. echo "Error: ". $_FILES["photo"]["error"];
  44. }
  45. }
  46. ?>

在上述脚本中,一旦我们提交表单,我们就可以通过PHP超级全局关联数组$_FILES来访问信息。除了使用$_FILES数组外,许多内置函数起着重要作用。

上传文件完成后,在脚本中,我们将检查服务器请求方法,如果是POST方法,则继续执行,否则系统将抛出错误。之后,我们访问$_FILES数组来获取文件名、文件大小和文件类型。一旦获取到这些信息,我们就对文件大小和类型进行验证。

最后,我们在要上传文件的文件夹中搜索,以检查文件是否已经存在。如果不存在,我们使用move_uploaded_file()将文件从临时位置移动到服务器上的目标目录,完成操作。