您是否曾经想知道PHP是如何构建文件上传系统的?在这里,我们将了解文件上传过程。您可能会问:“我们能否使用此系统上传任何类型的文件?”。答案是肯定的,我们可以上传不同扩展名的文件。
方法:要运行PHP脚本,我们需要服务器。因此,请确保在您的Windows计算机上安装了XAMPP服务器或WAMP服务器。
HTML代码片段:以下是将文件上传到服务器所需的HTML表单的HTML源代码。在HTML的<form>
标签中,我们使用“enctype=’multipart/form-data’”,这是一种允许通过POST方法发送文件的编码类型。没有这种编码,文件无法通过POST方法发送。如果您希望允许用户通过表单上传文件,则必须使用此enctype。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="file-upload-manager.php" method="post" enctype="multipart/form-data">
<!--multipart/form-data ensures that form data is going to be encoded as MIME data-->
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<!-- name of the input fields are going to be used in our php script-->
<p><strong>Note:</strong>Only .jpg, .jpeg, .png formats allowed to a max size of 2MB.</p>
</form>
</body>
</html>
现在,我们来编写一个能够处理文件上传系统的PHP脚本。 file-upload-manager.php
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Check if file was uploaded without errors
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)
{
$allowed_ext = array("jpg" => "image/jpg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"png" => "image/png");
$file_name = $_FILES["photo"]["name"];
$file_type = $_FILES["photo"]["type"];
$file_size = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed_ext))
die("Error: Please select a valid file format.");
// Verify file size - 2MB max
$maxsize = 2 * 1024 * 1024;
if ($file_size > $maxsize)
die("Error: File size is larger than the allowed limit of 2MB");
// Verify MYME type of the file
if (in_array($file_type, $allowed_ext))
{
// Check whether file exists before uploading it
if (file_exists("upload/".$_FILES["photo"]["name"]))
echo $_FILES["photo"]["name"]." already exists!";
else
{
move_uploaded_file($_FILES["photo"]["tmp_name"],
"uploads/".$_FILES["photo"]["name"]);
echo "Your file uploaded successfully.";
}
}
else
{
echo "Error: Please try again!";
}
}
else
{
echo "Error: ". $_FILES["photo"]["error"];
}
}
?>
在上述脚本中,一旦我们提交表单,我们就可以通过PHP超级全局关联数组$_FILES来访问信息。除了使用$_FILES数组外,许多内置函数起着重要作用。
上传文件完成后,在脚本中,我们将检查服务器请求方法,如果是POST方法,则继续执行,否则系统将抛出错误。之后,我们访问$_FILES数组来获取文件名、文件大小和文件类型。一旦获取到这些信息,我们就对文件大小和类型进行验证。
最后,我们在要上传文件的文件夹中搜索,以检查文件是否已经存在。如果不存在,我们使用move_uploaded_file()将文件从临时位置移动到服务器上的目标目录,完成操作。