2012-04-07 84 views
3

我试图把web图像保存到本地,我在这里使用代码来做判断,如果图像文件名结尾不是.jpg,.jpeg,.png或者.gif,请添加它们。我使用stripos,但遇到像这样的图像网址时遇到了一些麻烦。那么如何解决?谢谢。php检查图片文件名结尾是不是.jpg,.jpeg,.png或.gif。

$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 
    } 
} 
+1

一试,只是因为一个文件名以.jpg结尾并不能使它JPEG文件,更好地检查的MIME类型。 – 2012-04-07 09:27:15

回答

5

你可以尝试这样的

$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 
} 
+1

这是一个好方法,也许应该在数组中添加'JPG,JPEG,PNG,GIF' – 2012-04-07 12:02:28

+5

这对于“foo.bar.png”不起作用。 – 2012-04-08 06:54:16

+1

你必须改变没有点的文件名。否则,找到数组$ len =(sizeof($ ext))的长度,并用'end($ ext)'替换$ ext [1]和$ ext [$ len-1] – nithi 2012-04-09 04:48:27

1

此功能pathinfo可能会对您有所帮助。

+0

pathinfo是否正确处理像原始示例中的变量? – kingjeffrey 2012-04-08 07:13:50

5

为什么不使用的preg_match?

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

使用吊索

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 
} 

希望这将有助于!)

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

这既适用于JPG以及JPEG和用大写字母。 它还与文件名就像testing.the.bicycle.jpg

给上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); 
} 
+0

hello,什么是'(?:[\?\#]。*)?'for?我是一个正则表达式的新手。一些谷歌搜索后知道这是一个非捕获组。但没有明白这一点。你能告诉我吗? – tpk 2016-11-18 04:05:56

相关问题