如何使用PHP处理文件名中的引号

时间:2015-12-29 18:37:23

标签: php

我有一个功能可以使缩略图在99%的时间内都有效。在我尝试创建缩略图的400张图片中,只有2张失败了。这两张图片都有单引号,我想知道这是否是问题的根源?如果是,我该怎么做才能解决它?

<?php

$image = "542Cute pets' hilarious snail dwelling life (06).jpg";
$image = "598BK_Fish'n_Crisp.jpg";

if ($image) {
    make_thumb("uploads", "thumbnails", $image, 500);
    echo $image;
}

function make_thumb($imageFrom, $imageTo, $image, $thumbWidth) {

    /* read the source image */
    $getFrom = $imageFrom."/".$image;

    $imageType =  exif_imagetype($getFrom);

    if ($imageType == IMAGETYPE_JPEG) {
        $source_image = imagecreatefromjpeg($getFrom);    
    }
    else if ($imageType == IMAGETYPE_PNG) {
        $source_image = imagecreatefrompng($getFrom);   
    } 
    else if ($imageType == IMAGETYPE_GIF) {
        $source_image = imagecreatefromgif($getFrom);   
    } 

    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* find the "desired height" of this thumbnail, relative to the desired width  */
    $thumbHeight = floor($height * ($thumbWidth / $width));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($thumbWidth, $thumbHeight);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, 
                       $thumbWidth, $thumbHeight, $width, $height);

    /* create the physical thumbnail image to its destination */

    $dest = $imageTo."/".$image;

    if ($imageType == IMAGETYPE_JPEG) {
        imagejpeg($virtual_image, $dest);   
    }
    else if ($imageType == IMAGETYPE_PNG) {
        imagepng($virtual_image, $dest);  
    } 
    else if ($imageType == IMAGETYPE_GIF) {
        imagegif($virtual_image, $dest);  
    } 

} //end of function make_thumb($imageFrom, $imageTo, $image, $thumbWidth)

?>

注意: 我从数据库中获取图像名称。这就是数据库中的样子:

542Cute pets&#039; hilarious snail dwelling life (06).jpg
598BK_Fish&#039;n_Crisp.jpg

1 个答案:

答案 0 :(得分:1)

我可以安全地假设单引号与文件名中保留的内容非常相关,因此您可以尝试简单地用有效字符替换引号或将其完全删除:

$image = str_replace("'", "", $image); //remove entirely

str_replace上的第一个参数可能是您可能想要完全删除的字符数组:

$removeArray[] = "'";
$removeArray[] = '@';
$removeArray[] = "^"; 

$image = str_replace( $removeArray, "", $image);

这些过滤器显然应该在您提取或初始化实际文件名之后:

$image = "542Cute pets' hilarious snail dwelling life (06).jpg";
$image = str_replace("'", "", $image);

您也可以在此处查看有关删除引号的详情:removing single-quote

但是,在保存到数据库之前,您似乎已使用html实体转义了文件名。它实际上修改了您的实际文件名,以便它查找:

imagejpeg($virtual_image, "598BK_Fish&#039;n_Crisp.jpg"); //can't find this one, sorry. :(

什么时候应该寻找:

imagejpeg($virtual_image, "598BK_Fish&'n_Crisp.jpg"); //this exists!