你好,我一直在网页上工作,用户可以上传图像和应用程序,如word文件,ppt,pdf,excel文件等..但我不确定我的代码可以任何人请建议我更好,更安全的方式来处理这个问题。我想做mime检查不是从客户端,而是从服务器端。而且我希望上传的最大文件大小为7 MB。 这是我的代码可以任何人请建议我任何事情
$allowedExts = array("pdf", "doc", "docx","png","jpg","jpeg","gif");
$extension = end(explode(".", $_FILES["uploadpic"]["name"]));
if (($_FILES["uploadpic"]["type"] == "application/pdf") ||
($_FILES["uploadpic"]["type"] == "application/msword") ||
($_FILES["uploadpic"]["type"]
== "application/vnd.openxmlformats-officedocument.wordprocessingml.document") ||
($_FILES["uploadpic"]["type"] == "image/png") ||
($_FILES["uploadpic"]["type"]=="image/jpeg") ||
($_FILES["uploadpic"]["type"] == "image/jpg")
&& ($_FILES["uploadpic"] ["size"] < 7340032) &&
in_array($extension, $allowedExts))
{
if ($_FILES["uploadpic"]["error"] > 0)
{
echo 'error';
exit;
}
else
{
$filetname=$_FILES ['uploadpic']['tmp_name'];
$filename=$_FILES ['uploadpic']['name'];
$insert=move_uploaded_file($filetname,"folder/$filename");
$insertpostsandpic=mysql_query("insert into `database` (`id`,`name`,`date`)
values ('$id','$filename','$time')");
echo 'sucess'; exit;
}
} else{
echo 'fail';
exit;
}
答案 0 :(得分:0)
创建两个数组:一个具有可接受的扩展名,另一个具有已接受的mime类型。使用SplFileInfo::getExtension()
获取文件扩展名。
我建议使用以下代码:
$accepted_mimes = array(
'image/png',
'application/pdf',
'addyourown'
);
$accepted_extensions = array(
'png',
'pdf',
'addyourown'
);
$max_file_size = 7*1000*1000;
$file = $_FILES['filename']['tmp_name'];
$obj = new SplFileInfo($file);
$extension = $obj->getExtension();
$mime = $obj->getType();
$size = $obj->getSize();
if(!in_array($extension, $accepted_extensions))
{
echo 'Extension '. $extension .' not accepted';
}
if(!in_array($mime, $accepted_mimes))
{
echo 'Extension '. $mime .' not accepted';
}
if($size > $max_file_size)
{
echo 'File size exceeded maximum file size limit';
}