0

我有一个网站,允许用户上传照片。出于安全目的,我只希望用户能够上传 jpeg、gif 或 png 文件类型。我将如何编写这些条件?

到目前为止我所拥有的:

if ($_FILES['media']['size'] != 0 && //tests file type) {
    //the file is good, upload the file
}

谢谢!

4

5 回答 5

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 类型:按内容类型列出的 MIME 类型列表

于 2013-05-03T17:37:51.553 回答
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
}
于 2013-05-03T17:38:24.987 回答
1

最好的选择是@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
}
于 2013-05-03T17:54:39.393 回答
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
}
于 2013-05-03T17:41:20.537 回答
-5
$ext = substr($_FILES['media']['name'], -3)

然后检查。

您可以将其与一系列允许的扩展名进行比较。

$allowed = array('jpg', 'gif');

并使用 in_array 进行检查。只是一种方式,但我相信还有更多。

于 2013-05-03T17:37:23.590 回答