使用PHP上传DOC或PDF [英] Upload DOC or PDF using PHP

查看:305
本文介绍了使用PHP上传DOC或PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以上载图像,但是当我将图像类型从图像/jpg,图像/gif更改为应用程序/msword和应用程序/pdf时,它不起作用.这是我的代码.完全相同的代码适用于图像,但是对于上载docs和pdf,它输出无效文件".这里发生了什么?我的文件只有大约30kb,远远低于此处的文件大小限制.

I'm able to upload images fine, but when when I change the types from image/jpg, image/gif to application/msword and application/pdf, it doesn't work. Here's my code. The exact same code works for images, but for uploading docs and pdf, it outputs "Invalid File." What's going on here? My file is only approx 30kb and is well under the file size limit here.

$allowedExts = array("pdf", "doc", "docx"); 
$extension = end(explode(".", $_FILES["file"]["name"]));

if ( ( ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "text/pdf") ) 
&& ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts))
{      
 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); 
}
else
{
echo "Invalid file."
}

推荐答案

请勿使用['type']参数来验证上传.该字段是用户提供的,可以轻松伪造,从而允许上载任何类型的文件.参数['name']也是一样-用户提供的文件名.伪造也很简单,因此用户发送nastyvirus.exe并将其称为cutekittens.jpg.

Don't use the ['type'] parameter to validate uploads. That field is user-provided, and can be trivially forged, allowing ANY type of file to be uploaded. The same goes for the ['name'] parameter - that's the name of the file as provided by the user. It is also trivial to forge, so the user's sending nastyvirus.exe and calling it cutekittens.jpg.

验证上传的正确方法是使用服务器端的mime类型确定,例如通过 fileinfo ,加上适当的上传成功检查,您不会这样做:

The proper method for validating uploads is to use server-side mime-type determination, e.g. via fileinfo, plus having proper upload success checking, which you do not:

if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
   case 'image/jpeg':
   case 'application/pdf'
   case etc....
        $ok = true;
   default:
       die("Unknown/not permitted file type");
}
move_uploaded_file(...);

您还将用户提供的文件名用作move_uploaded_files最终目的地的一部分.将路径数据嵌入到该文件名中,然后盲目地使用它也是微不足道的.这意味着恶意的远程用户可以在服务器上知道其路径的任何文件上乱写乱画,并添加新文件.

You are also using the user-provided filename as part of the final destination of the move_uploaded_files. it is also trivial to embed path data into that filename, which you then blindly use. That means a malicious remote user can scribble on ANY file on your server that they know the path for, plus plant new files.

这篇关于使用PHP上传DOC或PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆