Why is this image validation and upload just not working
I am trying to create an Image validation and upload script.
I have 2 functions in my class at the moment to check for the image type and to actually make the upload.
I have 2 arrays one to specify the disallowed extentions and one to specify allowed image types
<?php
var $imageTypes = array("image/gif","image/jpg","image/jpeg","image/png");
var $badextentions = array(".php",".phtml",".php3",".php4");
?>
The first function is checking the image type and file extention
<?php
//check the file is a valid image type
private function file_type($file){
foreach($this->imageTypes as $type){
if($file['type'] != $type){
return FALSE;
}
}
foreach($this->badextentions as $item){
if(preg_match("/$item\$/i", $file['name'])){
return FALSE;
}
}
return TRUE;
}
?>
the second function makes the upload
<?php
public function upload_image(){
if(!isset($_FILE['image'])){
return FALSE;
}else{
$theimage = $_FILE['image'];
}
if(is_uploaded_file($theimage['name'])){
if($this->file_type($theimage) === FALSE){
return FALSE;
}else{
$uploadFile = move_uploaded_file($theimage, $imagefolder);
if($uploadFile){
return TRUE;
}else{
return FALSE;
}
}
}
return FALSE;
}
?>
Any help appreciated.
greg posted this at 16:35 — 10th December 2008.
He has: 1,581 posts
Joined: Nov 2005
You use
$_FILE['image'];
, firstly, is the input field in your form also called "image"?And second, shouldn't that be
$_FILES['image'];
(S)As I can't see the forum, i have to ask, does the form have
enctype="multipart/form-data"
, which is required.Here's some handy reading if you hadn't already found it
http://uk2.php.net/features.file-upload
pr0gr4mm3r posted this at 16:42 — 10th December 2008.
He has: 1,502 posts
Joined: Sep 2006
This block of code will always return false:
foreach($this->imageTypes as $type){
if($file['type'] != $type){
return FALSE;
}
}
The only way this could be true is if the image type of the uploaded image matched every type in your array.
Something like this would work:
$match = false;
foreach($this->imageTypes as $type){
if($file['type'] == $type){
$match = true;
}
}
return $match;
Greg K posted this at 18:39 — 10th December 2008.
He has: 2,145 posts
Joined: Nov 2003
in reference to the foreach above, even simpler would be:
$fileExt = substr($file['name'],strrpos($file['name'],"."));
return in_array($file['type'],$this->imageTypes) &&
!in_array($fileExt,$this->badextentions);
Note the use of strrpos(), this gets the LAST match of the period, not the first.
-Greg
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.