Home >Backend Development >PHP Tutorial >PHP identifies file camouflage (file upload)

PHP identifies file camouflage (file upload)

藏色散人
藏色散人forward
2020-01-27 15:11:182711browse

PHP identifies file camouflage (file upload)

Question:

When uploading files, it is necessary to verify whether the uploaded files are legal. How to identify file camouflage?

A simple test: change the txt file suffix directly to jpg; upload

<!DOCTYPE html>
<html>
    <title>test</title>
    <body>
        <form enctype="multipart/form-data" action="test.php" method="POST">
            <!-- MAX_FILE_SIZE must precede the file input field -->
            <input type="hidden" name="MAX_FILE_SIZE" value="102400" />
            <!-- Name of input element determines name in $_FILES array -->
            Send this file: <input name="userfile" type="file" />
            <input type="submit" value="Send File" />
        </form>
    </body>
</html>

1. Get the file suffix through $_FILES['userfile']['type'];

$data = $_FILES[&#39;userfile&#39;];
var_dump($data);
/**结果**/
/*
array(5) {
  ["name"]=>
  string(8) "test.jpg"
  ["type"]=>
  string(10) "image/jpeg"
  ["tmp_name"]=>
  string(26) "/private/var/tmp/phpfyE3EC"
  ["error"]=>
  int(0)
  ["size"]=>
  int(19)
}
*/

Not detected;

2. Use the pathinfo() function to obtain file path information

$data = $_FILES[&#39;userfile&#39;];
// var_dump($data);
var_dump(pathinfo($data[&#39;name&#39;]));
/**结果**/
/*
array(4) {
  ["dirname"]=>
  string(1) "."
  ["basename"]=>
  string(8) "test.jpg"
  ["extension"]=>
  string(3) "jpg"
  ["filename"]=>
  string(4) "test"
}
*/

Not detected;

3. PHP extension fileinfo (needs to be installed and enabled)

$data = $_FILES[&#39;userfile&#39;];
$filename = $data[&#39;tmp_name&#39;];
$finfo   = finfo_open(FILEINFO_MIME_TYPE);//返回 mime 类型。 自 PHP 5.3.0 可用。
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
var_dump($mimetype);
/**结果**/
//string(10) "text/plain"

Yes! Can! Can! It is detected that the file mime type is not a jpg!

For more related php knowledge, please visit php tutorial!

The above is the detailed content of PHP identifies file camouflage (file upload). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete