php 检查图像文件名结尾是否不是 .jpg、.jpeg、.png 或 .gif。

标签 php regex mime-types

我试过将网页图片保存到本地,我这里用代码来判断,如果图片文件名结尾不是.jpg,.jpeg,.png,.gif,就加上。我使用 stripos,但是当像这样的图片 url 时我遇到了一些麻烦。那么如何解决呢?谢谢。

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

最佳答案

你可以这样试试

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

关于php 检查图像文件名结尾是否不是 .jpg、.jpeg、.png 或 .gif。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052845/

相关文章:

php - 如何在 Windows 中运行 "brew"命令?

php - 如何强制 PHP 的 IntlDateFormatter 仅忽略输出中的年份?

python - 如何创建包含变量和注释的正则表达式?

regex - 匹配引号中的文本(新手)

javascript - 忽略正则表达式中的常规 HTML 标签

php - 如何在MySQL中搜索反斜杠(\)标记和零(0)?

php限制函数调用某些类

excel - Excel 文件的正确内容类型是什么?

mime-types - 通配符 MIME 子类型

java - 如何获取 Mime 类型(内容类型)的文件扩展名