I am writing a basic image upload script in PHP, and am looking for critiques. The script below is the result of various suggestions I have found online... for now I am running it locally and it works fine, but I would love for someone more experienced to look over it.
Is this secure? Poorly implemented? Too redundant? Not redundant enough? What am I missing and/or doing incorrectly? Any suggestions/help/advice is GREATLY appreciated. Thank you.
PHP:
if (isset($_FILES['image']))
{
$files_array = $_FILES['image'];
$num_of_image_uploads = count($files_array['name']);
// Loop through array of file uploads
for ($i = 0; $i < $num_of_image_uploads; $i++)
{
// Check if there is a file to upload
// If so -> define, validate, and upload
if ($files_array['tmp_name'][$i] != "")
{
$errors = false; // Flag for errors
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $files_array['name'][$i];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $files_array['size'][$i];
$file_tmp = $files_array['tmp_name'][$i];
// Extension check 1
if (in_array($file_ext, $allowed_ext) === false)
{
echo "Extension not allowed. <br/>";
$errors = true;
}
// Extension check 2 - if file is not empty
if ($file_size == 0)
{
echo "File is empty. <br/>";
$errors = true;
}
else if (!getimagesize($file_tmp))
{
echo "Not an image. <br/>";
$errors = true;
}
// Extension check 3
$blacklist = array(".php", ".phtml", ".php3", ".php4");
foreach ($blacklist as $item)
{
if(preg_match("/$item\$/i", $file_name))
{
echo "File not allowed. <br/>";
$errors = true;
}
}
// File size check
if ($file_size > 4718592)
{
echo "File size must be under 4.5MB. <br/>";
$errors = true;
}
// Rename file
$file_name = preg_replace("/[^A-Z0-9_]/i", "_", $file_name);
$file_name = md5($i.$file_name.time());
// Insert if no errors
if ($errors == false)
{
if (move_uploaded_file($file_tmp, 'uploads/'.$file_name.'.'.$file_ext))
{
echo "Success! File uploaded. <br/>";
}
}
}
}
}
HTML:
<body>
<form enctype="multipart/form-data" action="" method="post">
<input name="image[]" type="file" />
<input name="image[]" type="file" />
<input name="image[]" type="file" />
<input name="image[]" type="file" />
<input type="submit" value="Upload" />
</form>
</body>