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.

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

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.