問題:檔案上傳時候需要驗證上傳的檔案是否合法,檔案偽裝如何識別?
一個簡單測驗:把txt檔案后綴直接改成jpg;上傳
<!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="https://www.cnblogs.com/pawn-i/p/102400" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="https://www.cnblogs.com/pawn-i/p/Send File" />
</form>
</body>
</html>
1.通過$_FILES['userfile']['type'];獲取檔案后綴名;
$data = $_FILES['userfile']; 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) } */
T_T 沒有檢測出來;
2.用pathinfo()函式來獲取檔案路徑的資訊
$data = $_FILES['userfile']; // var_dump($data); var_dump(pathinfo($data['name'])); /**結果**/ /* array(4) { ["dirname"]=> string(1) "." ["basename"]=> string(8) "test.jpg" ["extension"]=> string(3) "jpg" ["filename"]=> string(4) "test" } */
T_T 沒有檢測出來;
3.PHP的擴展fileinfo(需要安裝開啟)
$data = $_FILES['userfile']; $filename = $data['tmp_name']; $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"
^_^ 可!可!可!監測到檔案mime型別并不是一個jpg!
最后附上PHP手冊介紹fileinfo的地址:https://www.php.net/manual/zh/book.fileinfo.php
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/91783.html
標籤:PHP
