php - 不需要在 PHP 中上传文件 - PHP FORM 不起作用
问题描述
我正在尝试创建一个可以上传文件的表单,但似乎我无法将此输入设为不需要的输入。每次我尝试验证没有上传的文件时,代码都会继续进入条件。
if (isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload']['name'])){
// Set files location
$target_dir = "media/";
$total = count($_FILES['fileToUpload']['name']);
$uploadOk = 1;
// Check if there is files to be uploaded.
if($total != 0) {
//$uploadOk = 1;
for($i=0; $i<$total; $i++) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$i]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$namee =$_FILES["fileToUpload"]["name"][$i];
// Check if file already exists
if (file_exists($target_file)) {
header('location: new_report.php?upload=fileexist');
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"][$i] > 500000) {
header('location: new_report.php?upload=toobig');
}
// Allow certain file formats
if($imageFileType != "png" && $imageFileType != "jpg" ) {
var_dump($_FILES['fileToUpload']['name']);
// exit;
header('location: new_report.php?upload=filenotallowed');
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $target_file)) {
Do something..
} else {
header('location: new_report.php?upload=error');
}
}
}
}
}
即使我不上传文件,我也会继续进入代码的执行部分。
html代码是:
<form action="submit_report.php" method="POST" enctype="multipart/form-data">
<input class="btn btn-primary" name="fileToUpload[]" type="file" multiple="multiple" id="fileToUpload">
</form>
用于多项选择文件
解决方案
制作文件isset
条件并尝试。
此代码经过测试
<?php
if (isset($_FILES['fileToUpload']))
{
if($_FILES['fileToUpload']['tmp_name'][0] == "") {
die("No files to upload");
}
foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key . $_FILES['fileToUpload']['name'][$key];
$file_size = $_FILES['fileToUpload']['size'][$key];
$file_tmp = $_FILES['fileToUpload']['tmp_name'][$key];
$file_type = $_FILES['fileToUpload']['type'][$key];
move_uploaded_file($file_tmp, getcwd() . "/" . time() . $file_name);
}
echo "Success";
}
else
{
echo "<form enctype='multipart/form-data' action='' method='POST'>";
echo "File:<input name='fileToUpload[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
echo "</form>";
}
?>
确保您的 HTML 表单应包含enctype="multipart/form-data"
推荐阅读
- java - 在 Kotlin 的同一个 Activity 中动态传递数据
- python - Brainfuck中优化的细胞增加
- dynamic - 带有“函数体返回 PL/SQL”的交互式网格列给出了引用列的错误(错误?)
- python - 顶级包之外的相对导入
- typescript - 如何在 Nestjs 测试中覆盖导入的模块?
- c++ - 需要帮助弄清楚如何使用 Qdial 更改我的 main 中的变量
- iframe - 第三方跟踪的跨域帧错误
- asp.net-core - ApiResource 返回“invalid_scope”身份服务器
- python - 如何将响应写入变量(Python、Tkinter)
- amazon-web-services - 通过 NAT-s 将静态 IP 分配给我由 Kops 管理的子网 - AWS