Frank Kluytmans
Frank Kluytmans

Reputation: 543

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.

Upvotes: 0

Views: 138

Answers (1)

Flosculus
Flosculus

Reputation: 6946

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']

Upvotes: 2

Related Questions