問題描述
我是一名 PHP 初學者,目前正在學習驗證文件上傳"部分.
I'm a PHP beginner and currently learning the "Validating the File Upload" part.
我做了一個包含以下代碼的 test.php 頁面:
I made a test.php page containing following code:
var_dump(@$_FILES['file']['type']);
首先,我上傳了一張圖片img.gif"并返回:
First, I uploaded an image "img.gif" and it returned:
string 'image/gif' (length=9)
然后,我將圖像的擴展名更改為.jpg"并返回:
Then, I changed the image's extension to ".jpg" and it returned:
string 'image/jpeg' (length=10)
所以我意識到 $_FILES["file"]["type"] 只返回上傳的文件擴展名,但實際上并沒有檢查它是什么文件.
So I realized $_FILES["file"]["type"] only return the uploaded file extension but didn't actually check what file is it.
在這個頁面,http://www.w3schools.com/php/php_file_upload.asp,有是代碼:
In this page, http://www.w3schools.com/php/php_file_upload.asp, there is a code:
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
我想知道為什么上面的代碼會檢查文件擴展名兩次?我從上面的代碼中刪除了一些,這是我的新代碼:
I'm wondering why above codes check file extension twice? I deleted some from above codes and this is my new code:
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if (($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts))
我的代碼正確嗎?或者你有什么更好的方法來驗證上傳的文件是圖片嗎?
Is my code correct? Or do you have any better ways to validate the upload file is a image?
謝謝!
推薦答案
您應該將文件的 tmp_name* 傳遞給 getimagesize,它會給你圖片的大小和類型(如果是圖片).如果傳遞的參數是文件而不是圖像,則返回 false,這將允許您進行驗證.
You should pass the tmp_name of the file* to getimagesize, it will give you the size and type of the image (if it is an image). If the passed argument is a file but not an image it returns false, that will allow you to validate.
圖像驗證唯一可靠的方法是使用 GD 或 Imagick 制作它的副本 - getimagesize 很容易被黑.
The only reliable method of image validation is to make a copy of it using GD or Imagick - getimagesize can be easily hacked.
*:我的意思是上傳后創建的臨時文件.
*: I mean, the temporal file created after upload.
例如:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = $_FILES['file']['tmp_name'];
if (file_exists($file))
{
$imagesizedata = getimagesize($file);
if ($imagesizedata === FALSE)
{
//not image
}
else
{
//image
//use $imagesizedata to get extra info
}
}
else
{
//not file
}
}
此代碼使用 file_exists 只是為了通用.如果沒有上傳文件,您將獲得 $_FILES['file']['size'] = 0
, $_FILES['file']['tmp_name'] = ''
和 $_FILES['file']['error'] = 4
.另請參閱is_readable.有關錯誤值,請參閱 文件上傳錯誤解釋,位于 php.net.
This code uses file_exists just to be general. In case no file were uploaded you would get $_FILES['file']['size'] = 0
, $_FILES['file']['tmp_name'] = ''
and $_FILES['file']['error'] = 4
. See also is_readable. For the error values see file upload errors explained at php.net.
這篇關于PHP 驗證文件上傳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!