10

我可以检查某个文件是否是图像吗?如何在 PHP 中做到这一点?

如果文件不是图像,我想发出警告消息。

4

5 回答 5

5

此外getimagesize(),您还可以使用exif_imagetype()

exif_imagetype() 读取图像的第一个字节并检查其签名。

当找到正确的签名时,将返回适当的常量值,否则返回值为 FALSE。返回值与 getimagesize() 在索引 2 中返回的值相同,但 exif_imagetype() 快得多。

对于这两个函数,如果文件未被确定为图像,则返回 FALSE。

于 2012-05-19T06:40:00.603 回答
2

在 PHP 中你可以像下面这样

if ((($_FILES['profile_picture']['type'] == 'image/gif') || ($_FILES['profile_picture']['type'] == 'image/jpeg') || ($_FILES['profile_picture']['type'] == 'image/png')))

在Javascript中你可以像下面这样

function checkFile() {
   var filename = document.getElementById("upload_file").value;
   var ext = getExt(filename);
 //  alert(filename.files[0].filesize);
  // alert(ext);
   if(ext == "gif" || ext == "jpg" || ext=="png")
      return true;
   alert("Please upload .gif, .jpg and .png files only.");
   document.getElementById("upload_file").value='';
   return false;
}

function getExt(filename) {
   var dot_pos = filename.lastIndexOf(".");
   if(dot_pos == -1)
      return "";
   return filename.substr(dot_pos+1).toLowerCase();
}
于 2012-05-19T06:36:33.683 回答
1

php我们可以使用filetype ( string $filename )mime_content_type ( string $filename )

但是mime_content_type ( string $filename )deprecated

http://php.net/manual/en/function.filetype.php

javascript我们可以使用自定义函数

http://my-sliit.blogspot.in/2009/04/how-to-check-upload-file-extension.html

于 2012-05-19T07:17:38.890 回答
0

我会这样做以找出...

$type =array('jpg','gif');

foreach($type as $val){

if($_FILES['filename']['type'] == 'image/$val')
{
echo "its an image file";
}
else{
echo "invalid image file"
}
于 2012-05-19T06:43:07.447 回答
0

更好更快的方法是使用exif_imagetype()。像这样的东西应该做的工作:

$valid_formats = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$file_format = exif_imagetype($filename);

if(!in_array($file_format, $valid_formats))
    echo("File format is not valid");
于 2017-02-13T06:54:02.987 回答