简体   繁体   中英

Only allow image files to be uploaded to my server with PHP

I'm trying to make a script in which I only allow .png, .jpeg and .gif files to be uploaded, based on MIME types. What I have so far is this:

if(file_exists($root."/upload/gallery/".$_FILES["image"]["name"]))
{
    $filename = explode(".",$_FILES['image']['name']);
    $randomnumber = rand(0, 10000);
    $imageName = $filename[0].$randomnumber.".".$filename[1];
}
else
{
    $imageName = $_FILES['image']['name'];
}

$image = mysql_real_escape_string(htmlspecialchars("/upload/gallery/".$imageName));

$allowed = array('image/jpeg', 'image/png', 'image/gif');

if(in_array($_FILES['image']['name'], $allowed)){
    echo "Allowed!";
    die;
}
else {
    echo "Not allowed!";
    die;
}

I was almost certain this should work. But it always echoes Not allowed! while I choose files with the correct MIME type, what am I doing wrong here? The code includes a check for files in my upload folder that already have the same name and if so adds a random number to the filename.

You are comparing the allowed list against the file name , not the type.

The type of the file will be contained in an array of applicable types in:

$_FILES['image']['type']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM