Secure User Image Upload Capabilities in PHP

后端 未结 4 1378
[愿得一人]
[愿得一人] 2020-12-01 14:45

I\'m implementing a user-based image uploading tool for my website. The system should allow any users to upload JPEG and PNG files only. I\'m, of course, worried about se

相关标签:
4条回答
  • 2020-12-01 15:25

    Concerning No. 2, I read on php.net (documentation of the function getimagesize() ):

    Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

    0 讨论(0)
  • 2020-12-01 15:31

    All the checks seem good, number 3 in particular. If performance is not an issue, or you are doing this in the background, you could try accessing the image using GD and seeing if it is indeed an image and not just a bunch of crap that someone is trying to fill your server with.

    0 讨论(0)
  • 2020-12-01 15:33

    Regarding your number 2), don't just check for FALSE. getimagesize will also return the mime type of the image. This is by far a more secure way to check proper image type than looking at the mime type the client supplies:

    $info = getimagesize($_FILES['userfile']['tmp_name']);
    if ($info === FALSE) {
        die("Couldn't read image");
    }
    if (($info[2] !== IMAGETYPE_PNG) && ($info[2] !== IMAGETYPE_JPEG)) {
        die("Not a JPEG or PNG");
    }
    
    0 讨论(0)
  • 2020-12-01 15:40

    Regarding file names, random names are definitely a good idea and take away a lot of headaches.

    If you want to make totally sure the content is clean, consider using GD or ImageMagick to copy the incoming image 1:1 into a new, empty one.

    That will slightly diminish image quality because content gets compressed twice, but it will remove any EXIF information present in the original image. Users are often not even aware how much info gets put into the Metadata section of JPG files! Camera info, position, times, software used... It's good policy for sites that host images to remove that info for the user.

    Also, copying the image will probably get rid of most exploits that use faulty image data to cause overflows in the viewer software, and inject malicious code. Such manipulated images will probably simply turn out unreadable for GD.

    0 讨论(0)
提交回复
热议问题