在Codeigniter中,如何检查上传的文件实际上是pdf还是jpg或png?因为,如果我们上传一个扩展名为.pdf的.exe文件,那么它也可以毫无问题地被上传。因此,它提供了一种正确检查文件及其内容的正确方法,从而能够确定它实际上是pdf还是exe。因为仅使用文件扩展名,任何内容都可以上传。请帮我找到一个合适的解决方案。是否有任何本机的php函数,我们可以通过它实现此目的。如果是这样,示例代码可能会有所帮助。
答案 0 :(得分:1)
您可以使用 mime_content_type()函数,该函数内置在php中,即使扩展名被更改,它也可以提供实际的内容类型 php docs
<?php
echo mime_content_type('abcd.pdf') //application/pdf
?>
上传时检查mime_content_type
$mimetype = mime_content_type($_FILES['file']['tmp_name']);
if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {
move_uploaded_file($_FILES['file']['tmp_name'], '/whatever/something/imagedir/' . $_FILES['file']['name']);
echo 'OK';
} else {
echo 'It is not an image';
}
答案 1 :(得分:0)
您需要像这样检查真实文件类型和给定的文件类型:
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$this->load->library('upload', $config);
$file = $_FILES['userfile'];
// given file type
$gftype=pathinfo($file['name'], PATHINFO_EXTENSION);;
// real file type
$rftype = explode('/',mime_content_type($file['tmp_name']))[1];
if($gftype === $rftype){
if (! $this->upload->do_upload('userfile')){
echo "Error";
}else{
echo "Success";
}
}else{
echo 'This is not real extension';
}