我有一个网站,我允许用户上传照片。出于安全考虑,我只希望用户能够上传jpeg,gif或png文件类型。我将如何写这些条件?
到目前为止我所拥有的:
if ($_FILES['media']['size'] != 0 && //tests file type) {
//the file is good, upload the file
}
谢谢!
答案 0 :(得分:2)
检查文件类型。
$fileType = $_FILES['media']['type'];
$fileSize = $_FILES['media']['size'];
if (fileSize != 0 ) {
if ($fileType == 'image/png' ||
$fileType == 'image/jpg' ||
$fileType == 'image/gif') {
//the file is good, upload the file
}
}
您可以在此处找到您的特定mime类型:List of MIME Types by Content Type
答案 1 :(得分:2)
使用$_FILES['media']['type']
所以你的完整代码:
if ($_FILES['media']['size'] != 0 && $_FILES["media"]["type"] == "image/jpeg" && $_FILES["media"]["type"] == "image/gif" && $_FILES["media"]["type"] == "image/png" ) {
//the file is good, upload the file
}
答案 2 :(得分:1)
最好的选择是@ Siamak.A.M提供给你但不是我在数组中使用mime / types字符串:
$fileType = $_FILES['media']['type'];
// add others.. and you can retrieve this from a conf. file too
$allowed = array('image/gif','image/jpg','image/png');
if (in_array($fileType, $allowed)) {
//the file is good, upload the file
}
答案 3 :(得分:0)
尝试
if ( $_FILES['media']['size'] != 0 && (
($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png") ) )
{
//the file is good, upload the file
}
答案 4 :(得分:-5)
$ext = substr($_FILES['media']['name'], -3)
然后检查一下。
您可以将其与允许的扩展数组进行比较。
$allowed = array('jpg', 'gif');
并使用in_array进行检查。只是一种方式,但我相信还有更多。