PHP Upload File Validation

前端 未结 2 554
时光说笑
时光说笑 2020-12-17 00:56

I am creating file upload script and I\'m looking for the best techniques and practices to validate uploaded files.

Allowed extensions are:

$allowed_         


        
相关标签:
2条回答
  • 2020-12-17 01:40

    Lots of file formats have a pretty standard set of starting bytes to indicate the format. If you do a binary read for the first several bytes and test them against the start bytes of known formats it should be a fairly reliable way to confirm the file type matches the extension.

    For example, JPEG's start bytes are 0xFF, 0xD8; so something like:

    $fp = fopen("filename.jpg", "rb");
    $startbytes = fread($fp, 8);
    $chunked = str_split($startbytes,1);
    if ($chunked[0] == 0xFF && $chunked[1] == 0xD8){
        $exts[] = "jpg";
        $exts[] = "jpeg";
    }
    

    then check against the exts.

    could work.

    0 讨论(0)
  • 2020-12-17 01:44

    If you want to validate images, a good thing to do is use getimagesize(), and see if it returns a valid set of sizes - or errors out if its an invalid image file. Or use a similar function for whatever files you are trying to support.

    The key is that the file name means absolutely nothing. The file extensions (.jpg, etc), the mime types... are for humans.

    The only way you can guarantee that a file is of the correct type is to open it and evaluate it byte by byte. That is, obviously, a pretty daunting task if you want to try to validate a large number of file types. At the simplest level, you'd look at the first few bytes of the file to ensure that they match what is expected of a file of that type.

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