Jump to content

Defining multiple values in an IF statement.


woolyg

Recommended Posts

Hi all,

 

I am writing a file upload script, but only want the file types to be jpg, gif or png. I want the script to basically say "If this file type is not a jpg, gif or png, then echo a rejection"

 

I'm using (and it's not working)

 

<?php

if($fileType != 'jpg', 'gif', 'png'){
echo "Wrong file type";
} else {
echo "Right file type";
}

?>

 

Anyone got any idea how to define more than one value into the IF statement, above?

 

All help appreciated,

Woolyg.

Either:

 

<?php
if($fileType != 'jpg' && $fileType != 'gif' && $fileType != 'png'){
echo "Wrong file type";
} else {
echo "Right file type";
}
?>

 

Or:

<?php
$extensions = array('jpg','gif','png');
if(!in_array($fileType,$extensions){
echo "Wrong file type";
} else {
echo "Right file type";
}
?>

 

Using an array will make things more manageable. Though it is also likely to be less efficient since you have to use the in_array() function. However, we're talking tiny differences here, so its largely irrelevant.

 

The proper way would be something like this

 

<?php

if($_FILES['FIELD_NAME']['type']=='image/gif' || $_FILES['FIELD_NAME']['type'] == 'image/jpeg') // check and see if the file type is an image
{
    echo 'File is a gif or jpg';

}
else
{
  echo 'File is not a jpg or gif';
}

?>

 

 

I believe that a png would be image/png so just add another one there.

 

Keep in mind that if the file upload field is blank, then it does not meet the criteria, so you may want to add a $_FILES['FIELD_NAME']['type']==''; part in there too.

 

Nate

I would highly suggest not relying on mime type sent from the browser, as not all browsers will send the mime type, and its easy to send say a PHP file as image/jpeg mime type.

 

I suggest sticking to file extensions, and you could also use exif_imagetype() or getimagesize() if you really want to determine if its an image and valid.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.