我试图在一个循环中上传多个图像,但出于某种原因,它会创建目录,上传1个文件并创建MySQL记录,所以我不确定为什么它只上传1个文件,即使当我打印$ I来查看有多少文件被计算时,它总是计算正确的数量。
PHP
function generateRandomString($length = 25) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
if (isset($_POST['newYoungSubmit'])) {
$imageDirectory = "images/youngMembers";
$newDirName = generateRandomString(20);
$postDate = date("Y-m-d");
$targetDir = $imageDirectory."/".$newDirName."/";
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
} else {
$newDirName = generateRandomString(20);
$targetDir = $imageDirectory."/".$newDirName."/";
}
// Count total files
$fileCount = count($_FILES['new_young']['name']);
// Iterate through the files
for($i = 0; $i < $fileCount; $i++){
$target_dir = $imageDirectory."/".$newDirName."/";
$target_file = $target_dir . basename($_FILES["new_young"]["name"][$i]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["new_young"]["tmp_name"][$i]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$errorTxt = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["new_young"]["size"] > 500000) {
// $errorTxt = "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$errorTxt = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
$temp = explode(".", $_FILES["new_young"]["name"][$i]);
$newfilename = round(microtime(true)) . '.' . end($temp);
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["new_young"]["tmp_name"][$i], $target_dir . $newfilename)) {
//echo "The file ". basename( $_FILES["new_young"]["name"]). " has been uploaded.";
} else {
$errorTxt = "Sorry, there was an error uploading your file.";
}
}
}
$newYoungQuery = $conn->prepare("INSERT INTO youngMembers (youngTitle, youngImgDir, youngDesc) VALUES (?,?,?)");
$newYoungQuery->execute([$_POST['youngTitle'], $targetDir, $_POST['youngDesc']]);
$newYoungQuery = null;
}