Paul Kumbweya
Paul Kumbweya

Reputation: 61

How do l make a function that validates and image

l have used the function below but its allowing even pdf to be uploaded and its not checking if its an image

function image_allowed($file_extn) {

        $allowed = array('jpg','jpeg','gif','png');

        $file_name =  $_FILES['image']['image_name'];

        $file_extn =  strtolower(end(explode('.', $file_name)));

        $file_temp = $_FILES['image']['tmp_name'];



if (in_array($allowed,$file_extn )=== true){
return true;



}else {
return false;


}

and l checked using the code below and l dont know were lam getting it wrong

if (image_allowed($_POST['image'])=== true) {
 $errors[] = ' images only are allowed.';

and l would love to know any checks that l might have ommited here

Upvotes: 0

Views: 45

Answers (3)

user3284566
user3284566

Reputation: 83

You need to use like this:

function image_allowed() {
    $allowed = array('jpg','jpeg','gif','png');
    $file_name =  $_FILES['image']['name'];
    $file_extn =  strtolower(end(explode('.', $file_name)));
    $file_temp = $_FILES['image']['tmp_name'];

    if (in_array($file_extn,$allowed)=== true){
        return true;
    }

     return false;
}

if (image_allowed()=== false) {
    $errors[] = ' images only are allowed.';
}else{
    //save image or something else
}

Upvotes: 0

Guilherme Ferreira
Guilherme Ferreira

Reputation: 143

You can check your image type using pathinfo (http://php.net/manual/en/function.pathinfo.php):

$path_parts = pathinfo('/your/image/path/');

echo $path_parts['extension']; // Your extension...

In your function code:

function image_allowed($imagePath) {
    $allowed = array('jpg','jpeg','gif','png');

    $myExtension = pathinfo($imagePath);

    if(in_array($myExtension['extension'], $allowed)
        return true;
    else
        return false;
}

Upvotes: 0

Ofir Baruch
Ofir Baruch

Reputation: 10346

While comparing extensions might do the trick, it's not very safe as it easy to fake an extension. I would advise to check the mime types of the files.

Option 1 - using finfo

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_type = finfo_file($finfo, "image.gif");
finfo_close($finfo);

Output for this case: image/gif

Just remember to change your $allowed array accordingly. You can see a list of possible mime types for images at wikipedia.

Option 2 - Using exif-imagetype

exif_imagetype('image.gif')

Just notice that in that case your $allowed array should contain constants that represent possible return values. (For further information look at the manual - link above)

Upvotes: 2

Related Questions