我有一个网站,允许用户上传照片。出于安全目的,我只希望用户能够上传 jpeg、gif 或 png 文件类型。我将如何编写这些条件?
到目前为止我所拥有的:
if ($_FILES['media']['size'] != 0 && //tests file type) {
//the file is good, upload the file
}
谢谢!
我有一个网站,允许用户上传照片。出于安全目的,我只希望用户能够上传 jpeg、gif 或 png 文件类型。我将如何编写这些条件?
到目前为止我所拥有的:
if ($_FILES['media']['size'] != 0 && //tests file type) {
//the file is good, upload the file
}
谢谢!
检查文件类型。
$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 类型:按内容类型列出的 MIME 类型列表
利用$_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
}
最好的选择是@Siamak.AM 提供给您,但我使用数组中的 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
}
尝试
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
}
$ext = substr($_FILES['media']['name'], -3)
然后检查。
您可以将其与一系列允许的扩展名进行比较。
$allowed = array('jpg', 'gif');
并使用 in_array 进行检查。只是一种方式,但我相信还有更多。