2

So I have have this script for uploading an image to a server. It allows jpg and png and renames the file to a random 6 digit number.

<?php
if (isset($_FILES['file'])) {
    $file       = $_FILES['file'];
    $file_name  = $file['name'];
    $file_tmp   = $file['tmp_name'];
    $file_size  = $file['size'];
    $file_error = $file['error'];

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

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

    if (in_array($file_ext, $allowed)) {
        if ($file_error === 0) {
            if ($file_size <= 10000000) {
                $file_name_new    = mt_rand(100000, 999999) . '.' . $file_ext;
                $file_destination = 'files/' . $file_name_new;
                if (move_uploaded_file($file_tmp, $file_destination)) {
                    echo "<a href='$file_destination'>$file_name_new</a>";
                }
            }
        }
    }
}
?>

Everything works great. It only allows files with the specified extension .jpg and .png.

Where I run into problems is you are able to rename a txt file such as script.txt to script.txt.jpg and the server will allow it, but it's not actually an image. This offers vulnerability to an attack.

Is there something I can add that will actually verify that the file being uploaded is an image? I heard something about getimagesize but i'm not sure. I'm pretty new to php.

Nick
  • 55
  • 8
  • Yes, `getimagesize` is usual practice for that. – Sergey Khalitov Jun 07 '16 at 04:20
  • Possible duplicate of [How to check if an uploaded file is an image without mime type?](http://stackoverflow.com/questions/6484307/how-to-check-if-an-uploaded-file-is-an-image-without-mime-type) – wpclevel Jun 07 '16 at 04:28

1 Answers1

0

You need to use the mimetype of the file to know what kind of file it is. The extension is not relevant.

Indeed, you can use getimagesize for this:

<?php 
    ...
$size = getimagesize($file_name)); 

switch ($size['mime']) { 
    case "image/gif": 
        echo "Image is a gif"; 
        break; 
    case "image/jpeg": 
        echo "Image is a jpeg"; 
        break; 
    case "image/png": 
        echo "Image is a png"; 
        break; 
    case "image/bmp": 
        echo "Image is a bmp"; 
        break; 
} 
?>

Source: http://php.net/manual/en/function.image-type-to-mime-type.php