Learning the best way to securely upload files to a server

Can someone tell me the best way to ensure that only image is uploaded using finfo() thereby preventing hackers from uploading 
a malicious files.Assuming I don't want to upload files outside the roots.

1: I check if file exist as follows


if(file_exists('upload/' . $_FILES['file_upload']['name'])){
    die('File with that name already exists.');
}

 2: I check files type
but I easily bypass this by changing the file type
[CODE]
 if ($_FILES['some_name']['type'] == 'image/jpeg') {  
       //Proceed to accept the file as a valid image
   }


3: Using getimagesize. 

This was easily bypassed also
[CODE]
$imageinfo = getimagesize($_FILES['image']['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg') {
echo "Sorry, we only accept<br> GIF and JPEG images<a href=lol.php><font color=red size=4>Back</font></a>";
exit;
}




Here is my problem using finfo
I tried using finfo but it does not allow images to be uploaded, can some tell me whats the problem with the finfo code below
[CODE]
   $finfo = new finfo(FILEINFO_MIME_TYPE);
   $fileContents = file_get_contents($_FILES['image']['tmp_name']);
   $mimeType = $finfo->buffer($fileContents);

if($finfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg') {
echo "Sorry, we only accept GIF and JPEG images";
exit;
}
Member Avatar for LastMitch

Can someone tell me the best way to ensure that only image is uploaded using finfo() thereby preventing hackers from uploading a malicious files.Assuming I don't want to upload files outside the roots.

@mutago

I'm having troubling reading your code.

You need to separate your own comments from the code comments, right now it's a mess.

If you want someone to help you then you need to post it nice and presentable or noone will bother reading it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.