我在网站上有一个文件上传系统,允许上传.doc,.docs和.pdf文件。目前,PHP脚本允许上传任何文件类型。我想将其限制为仅允许上传正版PDF DOC和DOCX文件。我已经读过,最好通过检查文件的MIME类型/标题来完成 - 但似乎无法找到一个商定的最佳解决方案来执行此操作。
有关实现此目标的最佳方法的任何提示?
当前上传的PHP是:
$meta = $dropbox->UploadFile($_FILES["fileInputFieldName"]["tmp_name"], $upload_name);
请注意有关如何将此功能整合到建议中的任何提示。
答案 0 :(得分:3)
为什么不尝试以下代码
$sys = mime_content_type($_FILES["fileToUpload"]["tmp_name"]);
if($sys == 'application/x-zip' || $sys == 'application/msword'){
echo ' allowed';
}else{
echo 'not allowed';
}
答案 1 :(得分:1)
我最终对那些感兴趣的人使用了这个:
$allowedExts = array(
"pdf",
"doc",
"docx"
);
$allowedMimeTypes = array(
'application/msword',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/x-pdf',
'application/vnd.pdf',
'text/pdf'
);
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( ! ( in_array($extension, $allowedExts ) ) ) {
die('Please provide another file type [E/2].');
}
if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) )
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
}
else
{
die('Please provide another file type [E/3].');
}
答案 2 :(得分:0)
that is how i restrict extension for image, you can apply this for doc and other files you want..
"i converted $_FILES to $file"
if ($file['profile_pic']['error'] == 0) {
// echo 'hello';
$fileName = strtolower($file['profile_pic']['name']);
$fileType = $file['profile_pic']['type'];
$tempName = $file['profile_pic']['tmp_name'];
$fileSize = $file['profile_pic']['size'];
$fileExtArray = array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'public.jpeg');
$random_no = mt_rand() * 64;
$uploaddir = '../../Application/img/';
$file_name = $random_no . "_profile_" . $_FILES['profile_pic']['name'];
$image = $uploaddir . basename($file_name);
if (in_array($fileType, $fileExtArray))
move_uploaded_file($_FILES['profile_pic']['tmp_name'], $image);
}
答案 3 :(得分:0)
$allowedExts = array("bmp", "gif", "jpg","png","jpeg");
$RandomNum = rand(0, 9999);
$ImageName = str_replace(' ','-',strtolower($_FILES['uploadedimage']['name']));
$ImageType = $_FILES['uploadedimage']['type']; //"document/txt", document/doc etc.
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
if (!empty($_FILES["uploadedimage"]["name"]))
{
if(!in_array($ImageExt, $allowedExts))
{
$message.="<span class='error-message'>Invalid file format of image, only <b>'bmp', 'gif', 'jpg','png','jpeg'</b> allowed.</span><br>";
}
}
if(isset($message) && $message=='')
{
//image
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imagename=time().'-'.$ImageName;
$target_path = "../profile-images/".$imagename;
$_SESSION['message']=$message;
}