If you want to only allow a few types of images, lets say: gif and jpg. You can create an array like:
$types = array('image/jpeg', 'image/gif');
Of course you can add more file types to your array as needed. Which can be found by doing a print_r on the $_FILES variable and taking the value from type.
Then when you upload your file to make sure that it is a correct file type you can do:
if (in_array($_FILES['inputname']['type'], $types)) {
// Your file handing script here
} else {
// Error, filetype not supported
}
then a php page called upload.php that the form above posts to.
the code was adapted from an about article.
<?php
$target = "images/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
//This is our size condition
if ($uploaded_size > 2097152){
echo "Your file is too large. We have a 2MB limit.<br>";
$ok=0;
}
$types = array('image/jpeg', 'image/gif', 'image/png');
if (in_array($_FILES['uploaded']['type'], $types)) {
// file is okay continue
} else {
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0){
Echo "Sorry your file was not uploaded. It may be the wrong filetype. We only allow JPG, GIF, and PNG filetypes.";
}
//If everything is ok we try to upload it
else{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else{
echo "Sorry, there was a problem uploading your file.";
}
}
?>
It also requires a folder called images with write permissions.
If you are just doing images, logic_earth’s code should work fine. You will have to write your code all over again on the occasion that you need to handle other file types.
It’s correct that you should never rely on information in the $_FILES array for security. If we had no ethics here, most of the experienced members of this board could easily show you how to use cURL or socket functions to spoof that information, and get an executable PHP file onto a server that only checks $_FILES for type information. Suffice it to say, you don’t want to know how easy it is.
Look at it this way. The web server is the gateway to your web site. The web server decides what to do with a file based on the file extension. If the file extension is JPG, it isn’t going to matter if it has PHP code in it or not. It’s not going to get executed as such.
The danger is in a file that might be called, hacktool.gif.php where your script only looks for the presence of the strings “jpg”, “gif” or “png”, instead of ensuring that that string is the “true” file extension.
As long as you don’t rely on the type information contained in the $_FILES array to ensure security, someone using cURL won’t be able to affect your script in that manner. If you detect an attempt to subvert your system, leave the file in the temp directory to die, or better yet delete it. Don’t leave it on your system to be exploited in some other way.