开发者

PHP not throwing exception on incorrect file upload size

开发者 https://www.devze.com 2023-02-11 11:05 出处:网络
I 开发者_开发问答have a simple form with a file upload input. This is the code that handles that form:

I 开发者_开发问答have a simple form with a file upload input. This is the code that handles that form:

$error = false;

if(isset($_POST["name"], $_POST["desc"], $_POST["aname"], $_FILES["skin"])) {
    try {
        // Validate the form
        if(strlen($_POST["name"]) < 3 || strlen($_POST["name"]) > 24)
            throw new Exception("Skin name needs to be between 3 and 24 characters.");
        if(strlen($_POST["desc"]) < 3 || strlen($_POST["desc"]) > 32)
            throw new Exception("Skin description must be between 3 and 32 characters.");
        if(strlen($_POST["aname"]) < 2 || strlen($_POST["aname"]) > 16)
            throw new Exception("Authors name must be between 2 and 16 characters.");

        // Validate the file upload
        if($_FILES["skin"]["error"] !== UPLOAD_ERR_OK)
            throw new Exception("There was a problem uploading the file. Try again later.");
        if($_FILES["skin"]["size"] > 204800)
            throw new Exception("File size must be 200KB or less.");

    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

And then later down in my code I have this:

if($error) {
    echo "<p class=\"error\">Error: <i>$error</i></p>";
}

Which displays an error above the form if an exception was thrown earlier in the code. Everything works fine apart from this section:

if($_FILES["skin"]["size"] > 204800)
    throw new Exception("File size must be 200KB or less.");

What I'm trying to do is detect if the file size of the uploaded file is more than 200KB. If it is, I want to throw an exception. But, if I send a 20MB file through the upload form, it doesn't catch it at all, and doesn't throw the exception.

Can anyone have a guess at why? I've already tried a few different combinations but for some reason it just doesn't detect it as over 200KB in size.

Any help is appreciated, thanks.

EDIT: Nevermind, I forgot to change the default php.ini setting that limits POST upload sizes. For anyone that ever has this problem, go into your php.ini file and change this option: post_max_size = 8M to something that suites your needs.


It seems you get empty $_FILES. This might happens if the posted file size exceeds post_max_size in php.ini.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号