Jump to content

Help validating uploaded files


coupe-r

Recommended Posts

Hi All,

 

I'm trying to validate file types and keep seeing an error.  I only allow .gif, .jpg or .png.  However, if I upload any of those file types, I get an error message....  If I echo out $filetypeCheck, I get image/png, which is corrent...

 

$filetypeCheck	= $_FILES["file"]["type"];

if( ($filetypeCheck != "image/gif") || ($filetypeCheck != "image/jpeg") || ($filetypeCheck != "image/png") )
{
$val_error[] = 'File Type Error! (.gif, .jpg and .png only)';
}

 

Whats going on here?

Link to comment
Share on other sites

The problem is with your condition statement

if( ($filetypeCheck != "image/gif") || ($filetypeCheck != "image/jpeg") || ($filetypeCheck != "image/png") )

 

NOTHING can pass that validation. If the image type was 'image/gif' then is does not equal 'image/jpeg' or 'image/png'. The problem is the OR statements and the negative checks. An image type will always not equal at least two of those consitions and validation fails. There are different solutions, such as

 

if( !($filetypeCheck == "image/gif" || $filetypeCheck == "image/jpeg" || $filetypeCheck == "image/png") ) {
    //Invalid image type
} else {
    //Valid image type
}

 

if( $filetypeCheck == "image/gif" || $filetypeCheck == "image/jpeg" || $filetypeCheck == "image/png") {
    //Valid image type
} else {
    //Invalid image type
}

 

Or my favorite

 

$validImageTypes = array('image/gif', 'image/jpeg', 'image/png');

if( !in_array($filetypeCheck, $validImageTypes)) {
    //Valid image type
} else {
    //Invalid image type
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.