共计 2305 个字符,预计需要花费 6 分钟才能阅读完成。
你是否想过网站如何应用 PHP 构建其文件上传零碎?在这里, 咱们将理解文件上传过程。你可能会想到一个问题 -“ 咱们是否能够 通过该零碎上传任何类型的文件?”。答案是能够的, 咱们能够上传具备不同扩展名的文件。
让咱们制作一个 HTML 表单, 用于 将文件上传到服务器。
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.");
// 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"]. "is already exists." ;
else
{move_uploaded_file( $_FILES [ "photo"]["tmp_name"], "uploads/" . $_FILES ["photo"]["name"]);
echo "Your file was uploaded successfully." ;
}
}
else
{echo "Error: Please try again." ;}
}
else
{echo "Error:" . $_FILES [ "photo"]["error"];
}
}
?>
在下面的脚本中, 一旦咱们提交了表单, 当前咱们就能够通过 PHP 超全局关联数组 $ _FILES 访问信息。除了应用 $ _FILES 数组的模式外, 许多内置函数也起着次要作用。上传完文件后, 在脚本中咱们将查看服务器的申请办法, 如果它是 POST, 则它将持续进行, 否则零碎将引发谬误。稍后, 咱们拜访了 $ _FILES 数组以获取文件名, 文件大小和文件类型。一旦取得了这些信息, 就能够验证文件的大小和类型。最初, 咱们在要上传文件的文件夹中搜寻, 以查看文件是否曾经存在。如果没有, 咱们曾经应用 move_uploaded_file()将文件从长期地位挪动到服务器上的所需目录, 咱们就实现了。
输入如下
更多后端开发相干内容请参考:lsbin – IT 开发技术:https://www.lsbin.com/
查看以下更多文件上传的相干的内容:
- Node.js 中的 formidable 模块上传文件:https://www.lsbin.com/2898.html
- Node.js 应用 Sharp 包进行图像上传:https://www.lsbin.com/1604.html
- PHP ftp_put()函数用法:https://www.lsbin.com/3352.html
正文完