How can I determine a file's true extension/type programmatically?

前端 未结 11 1332
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 17:06

I am working on a script that will process user uploads to the server, and as an added layer of security I\'d like to know:

Is there a way to detect a file\'s true e

11条回答
  •  误落风尘
    2020-12-01 17:28

    PHP has a superglobal $_FILES that holds information like size and file type. It looks like the type is taken form some sort of a header, not an extension, but I may be wrong.

    There is an example of it on w3schools site.

    I am going to test if it is can be tricked when I get a chance.

    UPDATE:

    Everyone else probably knew this, but $_FILES can be tricked. I was able to determine it this way:

    $arg = escapeshellarg( $_FILES["file"]["tmp_name"] );
    system( "file $arg", $type );
    echo "Real type:  " . $type;
    

    It basically uses Unix's file command. There are probably better ways, but I haven't used PHP in a while. I usually avoid using system commands if possible.

提交回复
热议问题