将上传白名单更改为黑名单

将上传白名单更改为黑名单

问题描述:

Instead of $allowed, I want to create $deny; instead of a whitelist, I want to make a blacklist. Mainly because I want to accept all files, except for exe, com, or whichever I choose.

<?php

// A list of permitted file extensions
$allowed = array('jpg','txt');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
        echo '{"status":"success"}';
        exit;
    }
}

echo '{"status":"error"}';
exit;

You want like this, i guess;

<?php

// A list of permitted file extensions
$denied = array('exe','com');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(in_array(strtolower($extension), $denied)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
        echo '{"status":"success"}';
        exit;
    }
}

echo '{"status":"error"}';
exit;

Just remove the negation (!) in the condition, and check that the uploaded file isn't one of the denied extensions:

if (in_array(strtolower($extension), $denied)) {
    echo '{"status":"error"}';
    exit;
}