how to check a file path is an image or not in php?

此生再无相见时 提交于 2019-12-10 22:19:56

问题


I have a table that stores file paths of images.documents,pdf etc... My query is

Select File_Paths from Uploads

Now how do I check whether the file path is image or not using PHP... If it is an image i have to view it or else download it.......


回答1:


Use the file info functions.




回答2:


Good old getimagesize() is a reasonable way to find out whether a file contains a valid image. You just need to test its return value against FALSE:

<?php

$is_picture = getimagesize($filename)!==FALSE;

?>

Of course, it's a good idea to do it only once and store the result into the database.

If this is not what you're looking for, please clarify.




回答3:


You need to check their extentions like this:

if (strpos($File_Paths, 'jpg') !== false || strpos($File_Paths, 'gif') !== false)
{
  // yes there is an image.
}



回答4:


You can chack extensions of the paths from the query. For example(using MySQL):

$result = mysql_query('Select File_Paths from Uploads');
$extArray = array('gif', 'jpg', 'jpeg', 'png');
while ($row=mysql_fetch_row($result)) {
  $extension = substr($row[0], strrpos($row[0], ".")+1);
  if (in_array($extension, $extArray)) {
    // Do something with image
  }
  else {
    // Download other files
  }
}


来源:https://stackoverflow.com/questions/2117396/how-to-check-a-file-path-is-an-image-or-not-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!