Ben
Ben

Reputation: 2564

Php file image upload security

$filename=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$extension=strtolower(substr($filename, strpos($filename, '.')+1));
$size=$_FILES['file']['size'];


if(($extension=='jpg' || $extension=='jpeg') && ($type!='image/jpg' || $type!='image/jpeg')){...

I have a input file, can let user upload jpg/jpeg image only, I have check type, extension, size.

  1. However I'm not sure how to check if user change extension.(ex. abc.php -> abc.jpg)

  2. any thing else I need to check before I save user's image into my server?

Upvotes: 2

Views: 475

Answers (3)

hungerstar
hungerstar

Reputation: 21685

@Fabian's answer looks good for checking the type of file. While I would suggest a different approach to getting the extension of the file.

Consider a file named stack.overflow.jpg.

$filename = 'stack.overflow.jpg';

// With your code $extension = 'overflow.jpg'
$extension=strtolower( substr( $filename, strpos( $filename, '.' ) +1 ) );

// With pathinfo() $extension = 'jpg'
$extension = pathinfo( $filename, PATHINFO_EXTENSION );

Consider using pathinfo() to get the file extension: http://www.php.net/manual/en/function.pathinfo.php

Upvotes: 0

Fabian
Fabian

Reputation: 3495

You can check the image with exif_imagetype()

http://www.php.net/manual/en/function.exif-imagetype.php

exif_imagetype() reads the first bytes of an image and checks its signature.

Upvotes: 3

Jake Aitchison
Jake Aitchison

Reputation: 1099

I would suggest using finfo:

<?php
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    foreach (glob("*") as $filename) {
        echo finfo_file($finfo, $filename) . "\n";
    }
    finfo_close($finfo);

    /* outputs:
    text/html
    image/gif
    application/vnd.ms-excel
    */
?>

example taken from php document site. see more info on the php document page http://www.php.net/manual/en/function.finfo-file.php

Upvotes: 2

Related Questions