Reputation: 3245
yesterday i started coding an upload file for uploading images to a directory. as i recognized that i have to use arrays to handle that a better way i got to the point that i'm using now:
if(!empty($_FILES['image']['tmp_name'])){
$allowed_extension = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
foreach($_FILES['image']['name'] as $key => $array_value){
$file_name = $_FILES['image']['name'][$key];
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$file_extension = strtolower(end(explode('.', $file_name)));
if (in_array($file_extension, $allowed_extension) === false){
$errors[] = 'file is not accepted';
}
if ($file_size > 2097152){
$errors[] = 'maxsize: 2MB';
}
$path = "a/b/c/";
$uploadfile = $path."/".basename($_FILES['image']['name'][$key]);
if (move_uploaded_file($_FILES['image']['tmp_name'][$key], $uploadfile)){
echo "Das Bildmaterial wurde hochgeladen.";
}
}
}
the problem is that i can upload the files all the time even when a non accepted ending is given. i dont understand why the upload happens when instead of uploading the errormessage should have been showed. i like to reach some more security with embedding allowed extensions to the code. if there is someone who could tell me what am i doing wrong, i would really appreciate. thanks a lot.
Upvotes: 1
Views: 1903
Reputation: 3799
You have two if-statements checking for exceptions but then do nothing with them.
Perhaps the following will help?
if(!empty($_FILES['image']['tmp_name'])){
$allowed_extension = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
foreach($_FILES['image']['name'] as $key => $array_value){
$file_name = $_FILES['image']['name'][$key];
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$errors = array ();
$file_extension = strtolower(end(explode('.', $file_name)));
if (in_array($file_extension, $allowed_extension) === false){
$errors[] = 'file is not accepted';
}
if ($file_size > 2097152){
$errors[] = 'maxsize: 2MB';
}
if (count ($errors) == 0) {
$path = "a/b/c/";
$uploadfile = $path."/".basename($_FILES['image']['name'][$key]);
if (move_uploaded_file($_FILES['image']['tmp_name'][$key], $uploadfile)){
echo "Das Bildmaterial wurde hochgeladen.";
}
}
else {
// do stuff with errors
}
}
}
Upvotes: 1
Reputation: 4011
You should use "continue"
eg
foreach($_FILES['image']['name'] as $key => $array_value){
$file_name = $_FILES['image']['name'][$key];
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$file_extension = strtolower(end(explode('.', $file_name)));
if (in_array($file_extension, $allowed_extension) === false){
$errors[] = 'file is not accepted';
continue;
}
// the rest of your loop goes here
}
It will then go to the next image in the loop and not upload the image.
More information here: http://php.net/manual/en/control-structures.continue.php
Upvotes: 1