我正在尝试创建一种可以上载文件的表单,但是看来我无法将此输入设为不需要的输入。每当我尝试验证是否没有上传的文件时,代码都会不断进入条件之中。
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>
是用于多选文件
答案 0 :(得分:1)
设置文件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"
答案 1 :(得分:0)
由于输入名称为fileToUpload[]
,所以将始终发布数组,因此您需要检查if count($_FILES['fileToUpload']) { ...
而不是使用isset($_FILES['fileToUpload'])
。