php 如何检查上传的文件类型是pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11039095/
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-24 23:38:34  来源:igfitidea点击:

how to check the uploaded file type is pdf

phphtmlpdf

提问by StaticVariable

Possible Duplicate:
How to check file types of uploaded files in PHP?

可能的重复:
如何在 PHP 中检查上传文件的文件类型?

I have uploading feature in my site and only pdf upload is allowed.Than how to check that the uploaded file is pdf only.Just like getimagesize()to ckeck the image files. Is there any way to check the file is sure to be pdf. my code is shown below.

我的网站有上传功能,只允许上传pdf。比如何检查上传的文件是否只有pdf。就像检查getimagesize()图像文件一样。有什么方法可以检查文件肯定是pdf。我的代码如下所示。

$whitelist = array(".pdf");

foreach ($whitelist as $item) {

    if (preg_match("/$item$/i", $_FILES['uploadfile']['name'])) {

    }
    else {

        redirect_to("index.php");
    }
}

$uploaddir='uploads/';

$uploadfile = mysql_prep($uploaddir . basename($_FILES['uploadfile']['name']));

if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) {

    echo "succussfully uploaded";
}

in this redirect_toand mysql_prepare function defined by me. But mime type can be changed using headers.So is there any way to check the file to be orignal pdf?

在这redirect_tomysql_prep是我定义的功能。但是可以使用标题更改 mime 类型。那么有什么方法可以检查文件是否为原始 pdf?

回答by Ben Evans

You can check the MIME type of the file using PHP's File Info Functions. If it returns with the type 'application/pdf' then it should be a PDF.

您可以使用 PHP 的文件信息函数检查文件的 MIME 类型。如果它以“application/pdf”类型返回,那么它应该是一个 PDF。

The File Info Functions were added in PHP 5.3 but previous to that you are able to use the mime_content_typefunction.

文件信息函数是在 PHP 5.3 中添加的,但在此之前您可以使用mime_content_type函数。

回答by HBv6

mime_content_type('file.ext');

mime_content_type()

mime_content_type()

回答by Mike

Look for the PDF magic numberby opening the file and reading the first few bytes of data. Most files have a specific format, and PDF files start with %PDF.

通过打开文件并读取数据的前几个字节来查找 PDF幻数。大多数文件都有特定的格式,PDF 文件以%PDF开头。

You can check the first 5 characters of the file, if they equal "%PDF-", it is likelya real PDF (however, this does not definitively prove that it is a PDF file, as any file can begin with those 5 characters). The next 4 characters in a proper PDF file contain the version number (i.e. 1.2).

您可以检查文件的前 5 个字符,如果它们等于“%PDF-”,则它可能是一个真正的 PDF(但是,这并不能完全证明它是一个 PDF 文件,因为任何文件都可以以这 5 个字符开头)。正确的 PDF 文件中接下来的 4 个字符包含版本号(即 1.2)。