如何在 php 中只允许某些文件类型上传?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2486329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:40:00  来源:igfitidea点击:

How can I only allow certain filetypes on upload in php?

phpuploadfile-type

提问by zeckdude

I'm making a page where the user upload a file. I want an if statement to create an $error variable if the file type is anything other jpg, gif, and pdf.

我正在制作一个用户上传文件的页面。如果文件类型是其他 jpg、gif 和 pdf,我想要一个 if 语句来创建一个 $error 变量。

Here's my code:

这是我的代码:

$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype

if(/*$file_type is anything other than jpg, gif, or pdf*/) {
  $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
}

I'm having difficulty structuring the if statement. How would I say that?

我在构建 if 语句时遇到困难。我怎么说呢?

回答by animuson

Put the allowed types in an array and use in_array().

将允许的类型放入数组中并使用in_array().

$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype

$allowed = array("image/jpeg", "image/gif", "application/pdf");
if(!in_array($file_type, $allowed)) {
  $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
}

回答by Carson Myers

edit

编辑

I just realized that you want to allow PDF files as well. In that case check out PHP's Fileinfo class and functions. But as far as security goes, you still shouldn't rely on $_FILES[]['type']:)

我刚刚意识到您也想允许 PDF 文件。在这种情况下,请查看PHP 的 Fileinfo 类和函数。但就安全而言,你仍然不应该依赖$_FILES[]['type']:)

I'll leave the rest here in case it helps someone else who finds this question

我会把其余的留在这里,以防它帮助发现这个问题的其他人



For checking the mime type of the image, $_FILES[]['type']could be unsafe. This data is sent by the browser and could be easily spoofed.

对于检查图像的 MIME 类型,$_FILES[]['type']可能不安全。这些数据是由浏览器发送的,很容易被欺骗。

You should use the getimagesize()function if you only want to allow images to be uploaded (despite its maybe misleading name). This function won't just give you the size but all the data you will probably need about the image.

getimagesize()如果您只想允许上传图像,则应该使用该功能(尽管它的名称可能具有误导性)。此功能不仅会为您提供大小,还会提供您可能需要的有关图像的所有数据。

I used the following script in an image handling class:

我在图像处理类中使用了以下脚本:

private function load_image_data($image_file) {

    // Firstly, to disambiguate a loading error with a nonexistant file error,
    // check to see if the file actually exists.
    if( ! file_exists($image_file) ) {
        throw new Nonexistent_Image_Exception("The file '{$image_file}' does not exist");
    }

    // We're going to check the return value of getimagesize, so we don't
    // need any pesky warnings or notices popping up, since we're going to
    // stop execution of this function if something goes wrong.
    $image_data = @getimagesize($image_file);

    if( $image_data === false ) {
        throw new Load_Image_Exception("Could not get image data from '{$image_file}'");
    }

    $this->size = new Dimensions($image_data[0], $image_data[1]);
    $this->mime = $image_data['mime'];

}

Notice that getimagesize()returns an associative array containing a 'mime' index. The data here is reliable.

请注意,它getimagesize()返回一个包含“mime”索引的关联数组。这里的数据是可靠的。

In another function I checked the mime type of the image and converted it to PNG with the appropriate GD function:

在另一个函数中,我检查了图像的 mime 类型并使用适当的 GD 函数将其转换为 PNG:

private function load_image($image_file) {

    // Suppress warning messages because we're going to throw an
    // exception if it didn't work instead.
    switch( $this->mime ) {
    case 'image/jpeg':
    case 'image/pjpeg':
        $this->image = @imagecreatefromjpeg($image_file);
        break;
    case 'image/gif':
        $this->image = @imagecreatefromgif($image_file);
        break;
    case 'image/png':
        $this->image = @imagecreatefrompng($image_file);
        break;
    default:
        throw new Invalid_Image_Exception("The image was of an invalid type");
    }

    if( $this->image === false ) {
        throw new Load_Image_Exception("Loading of image '{$image_file}' failed");
    }

}

You probably won't need to do all of this, but you can see what mime types appear for the filetypes you have specified. Notice that a jpeg could have two different mime types.

您可能不需要执行所有这些操作,但您可以查看为您指定的文件类型显示的 MIME 类型。请注意,jpeg 可以有两种不同的 mime 类型。

Hope this helps.

希望这可以帮助。

回答by raspi

See also Zend Framework's Zend_File_Transfer_Adapter_Httpand Zend_Form_Element_File. You can add multiple different validators like minimum image resolution, MIME type, minimum file size, allowed file extensions, etc.

另请参阅Zend FrameworkZend_File_Transfer_Adapter_HttpZend_Form_Element_File。您可以添加多个不同的验证器,例如最小图像分辨率、MIME 类型、最小文件大小、允许的文件扩展名等。

回答by Obaidul Haque

Use this simple code...

使用这个简单的代码...

<?
$path = $_FILES['file']['name']; // file means your input type file name
$ext = pathinfo($path, PATHINFO_EXTENSION);

if ($ext=="jpg" OR $ext=="jpeg" OR $ext=="gif" OR $ext=="png") {
    // your code here like...
    echo "Upload successful";
}else{
    // your invalid code here like...
    echo "Invalid image format. Only upload JPG or JPEG or GIF or PNG";
}
?>