[英]How to check the file type of the file upload in HTML form?
这是文件上传代码。 它以接受所有图像扩展名的方式工作。 但是它需要验证文件类型(视频,word doc等)。 我只需要上传图片就可以了。 例如,现在发生的情况是,当我选择一个Word文档并提交表单时,它会显示一堆错误,并插入记录而不是文件。 应该发生的是,如果文件不是图像,则文件不应允许用户插入记录。 提交表单时,应该收到一条错误消息,提示您检查文件类型。 请协助我实现这一目标。
if( isset($_FILES['img']) )
{
//resizing the image
$image = new SimpleImage();
$image->load($_FILES['img']['tmp_name']);
$image->resizeToHeight(180);
$info = pathinfo($_FILES['img']['name']);
$file = 'uploads/' . basename($_FILES['img']['name'],'.'.$info['extension']) . '.png';
if ($image->save($file))
{
if($fp = fopen($file , 'rb'))
{
$data = fread($fp, filesize($file));
//encoding the the image only to text so can be stored in DB
$data = base64_encode($data);
fclose($fp);
}
}
else
{
$error = '<p id="failed">Invalid Image</p>';
}
在较早的PHP版本中,可以使用mime_content_type
。 但是,如果您的PHP> 5.3,则应使用finfo_*
函数
您还应该检查is_uploaded_file()
而不是isset()
if( is_uploaded_file( $_FILES['img']['tmp_name'] ) ) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file( $_FILES['img']['tmp_name'] );
if( $type == 'image/gif' ) { // for example
// do stuff
}
}
您需要检查图像上的MIME类型,如下所示:
if (isset($_FILES['img'])) {
$file = $_FILES['img'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (strpos($mime, 'image') === false) {
die('The submitted file is not an image!');
}
// Uploading code..
}
如果mime字符串中包含“图像”,则为图像。 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.