PHP form type validation

Hey ya’ll I’m try to do a file type validation in a file upload PHP script. This is the script I am using. It doesn’t return any errors but it doesn’t work either!

} elseif (isset($_FILES['upload'])) {
	//bail out if the file isn't really an upload
	if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
	exit('There was no file uploaded!');
	} 
//Check for file formatting
if (preg_match('/^image/p?jpeg(;.*)?$/', $_FILES['upload']['type'])
	or preg_match('/image/gif(;.*)?$/', $_FILES['upload']['type'])) {
} else {
	echo "<p>Please submit a JPEG or GIF image file.</p>\
";
	}

I am using preg_match because regexi is deprecated, I think.
Thanks Bob

O.K. now I’m convinced I must have this in the wrong position in the script. If I put it at the start of the script right after the database connect statement I get an error of “undefined index: upload in C:\wamp\www\fileuploadcomp.php on line 22.” This index must be defined later in the script because if I place the reg exp statement below the file upload part of the script it doesn’t give me an error but it doesn’t stop the file from uploading either. I can post the entire script if it would help. Thanks so much.

some other basic samples


if(!preg_match('/^image\\/(pjpeg|jpeg|gif)$/i',$_FILES['upload']['type'])){
	exit('error');
}


$types = array( 'image/pjpeg','image/jpeg','image/gif' );
if (!in_array( $_FILES['upload']['type'],$types )) {
	exit('error');
}

Hey Blaine thanks for the quick response. I changed the script to reflect your suggestions, but it still doesn’t work. It continues even if the file is something other than jpg or gif. I even changed the script to
<?PHP
$type = “image/giff”;
if (!preg_match(‘/^image\/p?jpeg(;.)?$/‘, $type)
or !preg_match(’/^image\/gif(;.
)?$/’, $type)) {
exit("<p>Please submit a JPEG or GIF image file.</p>
");
} else {
echo “correct”;
}
But then the script never proceeds beyond the exit no matter if the file is a jpg or gif.
Curious-er and curious-er!!

Putting up the error would help. Try this:

<?PHP
$type = "image/giff";
if (!preg_match('/^image\\/p?jpeg(;.*)?$/', $type)
	or !preg_match('/^image\\/gif(;.*)?$/', $type)) {
	echo "<p>Please submit a JPEG or GIF image file.</p>\
";
} else {
	echo "correct";
}

O.K. I changed it to this but it still doesn’t work!! It allows me to upload any file type I want. Thanks for the help.

//Check for file formatting
$pattern = "/^[a-zA-Z0-9._-]+\\.{gif|jpg|jpeg}$/";
if (preg_match($pattern, $_FILES['upload']['type'])) { 
 } else { 
	exit('<p>Please submit a JPEG or GIF image file.</p>');
	}
	
} elseif (isset($_FILES['upload'])) {
	//bail out if the file isn't really an upload
	if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
	exit('There was no file uploaded!');
	}