设置最大文件大小 PHP

时间:2021-04-21 23:21:23

标签: php wamp

我正在创建一个社交网站,并试图限制用户可以上传的文件大小。我已经知道如何更改 wamp/xamp 设置中的 upload_max_filesize,但是有没有办法手动执行此操作?例如设置最大值为 8mb,但我可以手动将其设置为 7.5mb 或 PHP 文件本身中的某些内容吗?这就是我尝试的方式:

$file_size = $_FILES['files']['size'];
$maxsize = 1048576;

if($_FILES['files']['size'] > $maxsize) {

    $errors = "Your file is to large";
}

我还用 $_FILES['files']['size'] 替换了 $file_size。我也试过:

if ($file_size > 15097152) {

    $errors = 'File cannot be larger than 1MB';
}

谢谢。

编辑


<input name="files[]" id='files' accept="image/png,image/gif,image/jpeg" type="file" multiple="multiple" />

$date_time = date('Y-m-d_H-i-s');
$img_limit = 10;
$maxsize = 3367463;

if(isset($_POST['submit'])) {

    $errors = [];
    $file_name = count($_FILES['files']['name']);
    $file_size = $_FILES['files']['size'];
    
    //$file_type = $_FILES['files']['type'];
    $imageFileType = pathinfo($file_name, PATHINFO_EXTENSION);

    if (strtolower($imageFileType) != "jpeg"&& strtolower($imageFileType) != "jpg" && 
        strtolower($imageFileType) != "png" && strtolower($imageFileType) != "gif") {

        $errors = "File type not allowed.";
    }

    if($_FILES['files']['size'] >= $maxsize) {

        $errors = "Your file is to large";
    }

    if ($img_limit > 10) {

        $errors = 'Cannot upload more than 10 images';
    }
    // Loop through each file
    for( $i=0 ; $i < $file_name ; $i++ ) {

        //Get the temp file path
        $file_tmp = $_FILES['files']['tmp_name'][$i];

        //Make sure we have a file path
        if (!$errors || $file_tmp != "") {

            $picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
            $uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);

            $file_path = "uploads/" . $picToUpload;

            $stmt = $con->prepare("INSERT INTO images (image) VALUES (?)");
            $stmt->bind_param('s', $file_path);
            $stmt->execute();
            //$stmt->close();
            header('Location: index4.php');
            exit();
        }
    }
}

$_SESSION['error'] = '<b><p style="color: #000; font-size: 30px; top: 34%;right: 50%;position: absolute;">
' . $errors . '</p></b>';
header('Location: index4.php');
exit();

1 个答案:

答案 0 :(得分:2)

您需要将验证检查放在处理每个文件的 [{"id":1,"transmission":"manual"}, {"id":2,"isDocked":true}] 循环中。

此外,您对图像数量的限制是错误的。您需要比较上传到 for 的文件数量,而不是将 $img_limit 与您初始化它的相同值进行比较。

我已经采取了重定向并退出循环,因为这将在上传第一个文件后重定向。我还将 $img_limitprepare 排除在循环之外,因为可以对每个文件使用相同的准备语句。

bind_param
相关问题