如何编辑我的代码以在至少有1个文件无效时停止上传允许的文件


How to edit my code to stop uploading of allowed file when at least 1 of them is not valid?

我有以下代码,用于从两个输入上传两个文件。(没有倍数)。

问题是,如果一个文件是正确的,而另一个文件不是,例如一个是.jpg,另一个是.exe,则上载.jpg而不上载.exe。

我如何编辑我的代码,以便如果两个文件中至少有一个不正确,则不会上传任何内容并显示相应的消息?

如果两个文件都正常,则继续上载。

消息:1。文件2太大。没有有效的扩展

$valid_formats = array("jpg", "gif", "zip", "bmp", "pdf", "doc", "docx");
$max_file_size = 1024*300; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

    // Loop $_FILES to execute all files
    foreach ($_FILES['files']['name'] as $f => $name) { 

            if ($_FILES['files']['size'][$f] > $max_file_size) {
                header("Location: http://www.");
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                header("Location: http://www.");
            }
            else{ // No error found! Move uploaded files 
            $random = rand(1,30);
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$random.$name)) {
                    $count++; // Number of successfully uploaded files
                    header("Location: http://www.");
                }
            }
    }

您需要在一个单独的循环中完成:

$valid_formats = array("jpg", "gif", "zip", "bmp", "pdf", "doc", "docx");
$max_file_size = 1024*300; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;
foreach ($_FILES['files']['name'] as $f => $name)
{
    if ($_FILES['files']['size'][$f] > $max_file_size)
    {
        header("Location: http://www.");
        exit();
    }
    elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) )
    {
        header("Location: http://www.");
        exit();
    }
}
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name)
{
    $random = rand(1,30);
    if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$random.$name))
    {
        $count++; // Number of successfully uploaded files
        header("Location: http://www.");
    }
}

move_uploaded_file应该在for each之外。循环一次以确保所有内容都有效,第二次则实际移动上传。

如果原始循环有任何错误,则不应运行第二个循环