PHP identifies file camouflage (file upload)

藏色散人
Release: 2023-04-08 10:46:01
forward
2678 people have browsed it

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>
Copy after login

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)
}
*/
Copy after login

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"
}
*/
Copy after login

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"
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template