Php check if the image file name is .jpg, .jpeg, .png or .gif.

I tried to save the web image to local, I am using the code here to make the judge, if the image file name is not specified .jpg, .jpeg, .png or .gif add them. I use stripos

, but I meet some problems when the image looks like this. So how do you decide? Thank you.

$webimage = 'http://pcdn.500px.net/5953805/d0dd841969187f47e8ad9157713949b4b95b3bda/4.jpg?1333782904356';
$pieces = explode("/", $webimage); 
$pathend = end($pieces);
$imageinfo = @getimagesize($webimage);
$imagetype= $imageinfo['mime'];
if($imagetype=='image/jpeg'){
    if(stripos($pathend,'.jpg')==0){
        $newpathend = $pathend.'.jpg'; // if image end is't '.jpg', add '.jpg'
    }else if(stripos($pathend,'.jpeg')==0){
        $newpathend = $pathend.'.jpeg'; // if image end is't '.jpg', add '.jpeg'
    }else{
        $newpathend = $pathend;// if image end is '.jpg' or '.jpeg', do not change
    }
}
if($imagetype=='image/png'){
    if(stripos($pathend,'.png')==0){
        $newpathend = $pathend.'.png'; // if image end is't '.png', add '.png'
    }else{
        $newpathend = $pathend;// if image end is '.png', do not change
    }
}
if($imagetype=='image/gif'){
    if(stripos($pathend,'.gif')==0){
        $newpathend = $pathend.'.gif'; // if image end is't '.gif', add '.gif'
    }else{
        $newpathend = $pathend;// if image end is '.gif', do not change
    }
}

      

+3


source to share


6 answers


You can try like this



$type=Array(1 => 'jpg', 2 => 'jpeg', 3 => 'png', 4 => 'gif'); //store all the image extension types in array

$imgname = ""; //get image name here
$ext = explode(".",$imgname); //explode and find value after dot

if(!(in_array($ext[1],$type))) //check image extension not in the array $type
{
    //your code here
}

      

+5


source


Why not use preg_match?



if( preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $webimage, $matches) ) {
    // matching file extensions are in $matches[1]
}

      

+5


source


This pathinfo function can help you.

+1


source


This works for both jpg and jpeg and capital letters. It also works with filenames liketesting.the.bicycle.jpg

Try https://regex101.com/r/gI8uS1/1

public function is_file_image($filename)
{
   $regex = '/\.(jpe?g|bmp|png|JPE?G|BMP|PNG)(?:[\?\#].*)?$/';

   return preg_match($regex, $filename);
}

      

+1


source


Use slings

if (strpos($your_text,'.png') !== false) {
        //do something
 } else if (strpos($your_text,'.jpg') !== false) {
        //do something
 } else if (strpos($your_text,'.gif') !== false) {
        //do something
 }

      

Hope this helps!)

0


source


$Extension=strrev(substr(strrev($fileName),0,strpos(strrev($fileName),'.')));
if(preg_match('/png|jpg|jpeg|gif/',$Extension))
{ 
    true 
}
else
{ 
    false
}

      

-1


source







All Articles