Check picture file type and size before file upload in php

后端 未结 7 1576
走了就别回头了
走了就别回头了 2020-12-09 13:41

I have the following code:

$filecheck = basename($_FILES[\'imagefile\'][\'name\']);
  $ext = substr($filecheck, strrpos($filecheck, \'.\') + 1);
  if (($ext          


        
7条回答
  •  情话喂你
    2020-12-09 14:21

    The comparisons like $ext == "jpg" only check that the $ext is exactly "jpg".

    You might want to use strtolower on $ext before doing those comparisons, to deal with the ".JPG" situation.


    If you are using PHP <= 5.2, you might want to use mime_content_type to check the content-type of the files, instead of relying on $_FILES['imagefile']['name'] and/or $_FILES["imagefile"]["type"], which are both sent by the client -- and can, as such, be faked.

    If you are using PHP >= 5.3, you might want to consider the new extension fileinfo, and it's finfo_file function


    For the size of the file, you are already using $_FILES["imagefile"]["size"] ; that's OK, I guess, but you will only know it when the file has been uploaded -- still, there is no real way of checking that kind of thing before upload, I'm afraid...


    you might be able to find some JS code to do a first pre-check of extension before the file is uploaded -- but you'll still have to check on the server side, as anything done client-side is inherently not secure.

    Not sure you could do the same about the file's size, though...

    Some browsers might support a hidden field called MAX_FILE_SIZE (see the documentation about file upload) ; but not sure it is really supported (never seen it used, actually ; so probably isn't :-( )


    As a sidenote, you will probably want to configure upload_max_filesize, so it allows upload at least as big as what you want (by default, it is generally set to 2MB ; so should already be OK for you)

提交回复
热议问题