我使用PHP将多个文件上传到文件夹。上传完成后,我收到上传的每个文件的浏览器消息。我的问题是如何在完成时为所有人提供消息,如果有错误只显示哪些文件没有上传。这是我的下面的脚本,并提前感谢
<?php
// Count # of uploaded files in array
$total = count($_FILES['filesToUpload']['name']);
// Loop through each file
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
?><script>alert('successfully uploaded');</script><?php
} else {
?><script>alert('error while uploading file');</script><?php
}
}
}
?>
答案 0 :(得分:1)
只需制作一个简单的变量$error
和$succes
。您可以在事后(当您的循环结束时)显示那些。我现在已经分别打印了每个错误和成功,你可以用这些数组做任何你想做的事情。
<?php
$total = count($_FILES['filesToUpload']['name']);
$succes = [];
$error = [];
for($i=0; $i<$total; $i++) {
$tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$succes[$_FILES['filesToUpload']['name'][$i]] = true;
}else{
$errors[$_FILES['filesToUpload']['name'][$i]] = true;
}
}
}
foreach(array_keys($succes) as $suc){
echo $suc." was succesfull";
}
foreach(array_keys($errors) as $error){
echo $error." failed to upload";
}
?>
答案 1 :(得分:0)
如果您仍希望使用警报执行此操作,可以根据成功或失败将文件名称传递给变量,并在退出for循环后将其包含在警报中。
$successfulmsg="Successfully uploaded: ";
$failedmsg="error while uploading files: ";
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$successfulmsg.=$_FILES['filesToUpload']['name'][$i];
}
else
{
$failedmsg.=$_FILES['filesToUpload']['name'][$i];
}
}
}
echo '<script>alert("'.$successfulmsg.'. And '.$failedmsg.'")</script>';