首页 > 解决方案 > PHP $_FILES 大小 总问题

问题描述

我有一个 HTML 表单,它将表单值和文件上传到 PHP 进行处理。我想做的一项检查涉及获取所有上传文件的总大小。如果 size 数组中的值都不为 0,那么我在下面的这段代码可以正常工作,但如果它们中的任何一个为 0(当文件输入留空时发生),那么由于某种原因,总数总是输出为 0。

代码:

    if (!empty($_FILES['attachment'])) { //If there are attachments
        $count = count($_FILES['attachment']['name']);
        if ($count > 0) {
            for ($i = 0; $i < $count; $i ++) {
                if (!empty($totalFileSize)){
                    $totalFileSize = 0;
                }
                //Total File Size
                if ($_FILES["attachment"]["size"][$i] != 0){
                    $totalFileSize += ($_FILES["attachment"]["size"][$i]);
                }
            }
            $message = $totalFileSize;
        }

        //Checks
        if ($totalFileSize > 20971520){
            $fileSizeError = 1;
        }
    }

    echo '<pre>'; print_r($_FILES['attachment']); echo '</pre>';
    echo $totalFileSize;
    exit();

输出:

Array
(
    [name] => Array
        (
            [0] => Image Today at 10_02_27.JPG
            [1] => 
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] => 
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpfJo8Fl
            [1] => 
        )

    [error] => Array
        (
            [0] => 0
            [1] => 4
        )

    [size] => Array
        (
            [0] => 982518
            [1] => 0
        )

)
0

我不明白为什么如果没有 0,for 循环中的附加项可以正常工作,但如果有则不行。

标签: phphtmlforms

解决方案


首先,如果您要使用,+=那么您必须先初始化该变量,然后再执行第一个+=

$totalFileSize其次,你有这条线,在循环中,如果值存在并且> 0 ,它将把值设置为零。

if (!empty($totalFileSize)){
    $totalFileSize = 0;
}

所以将代码更改为

$totalFileSize = 0; // init before using `+=`

if (!empty($_FILES['attachment'])) { //If there are attachments
    $count = count($_FILES['attachment']['name']);
    if ($count > 0) {
        for ($i = 0; $i < $count; $i ++) {
            //Total File Size
            if ($_FILES["attachment"]["size"][$i] != 0){
                $totalFileSize += ($_FILES["attachment"]["size"][$i]);
            }
        }
        $message = $totalFileSize;
    }
    //Checks
    if ($totalFileSize > 20971520){
        $fileSizeError = 1;
    }
}

这可以简化为

$totalFileSize = 0; // init before using `+=`

if (!empty($_FILES['attachment'])) { //If there are attachments
    foreach( $_FILES['attachment']['size'] as $size){
        //add up the File Sizes
        $totalFileSize += $size;
    }
    $message = $totalFileSize;
    //Checks
    if ($totalFileSize > 20971520){
        $fileSizeError = 1;
    }
}

甚至

if (!empty($_FILES['attachment'])) { //If there are attachments
    $totalFileSize = array_sum($_FILES['attachment']['size']){
    //Checks
    if ($totalFileSize > 20971520){
        $fileSizeError = 1;
    }
}

甚至

if (!empty($_FILES['attachment'])) { //If there are attachments
    if (array_sum($_FILES['attachment']['size']) > 20971520){
        $fileSizeError = 1;
    }
}

推荐阅读