查找文件是否存在,如果不存在,则恢复到原始路径

发布于 2024-10-15 17:02:31 字数 1237 浏览 6 评论 0原文

我编写了一个函数来获取图像路径,在其末尾添加一些文本,然后将其重新连接在一起。我正在尝试编写一个 if else 分支来测试在将新文本附加到图像后文件是否存在。

例如,如果我请求图像路径:

http://example.com/image1.jpg

可以修改为:

http://example.com/image1-150x100.jpg

该函数适用于 WordPress,因此采用 $post->ID 参数、自定义字段名称、预期目标的宽度和高度。

这是函数:

function get_galleria_image ( $post_id, $customFieldName, $width, $height ) {

    $imagePath = get_post_meta($post_id, $customFieldName, true);

    $splitImage = explode('.', $imagePath);

    $count = count($splitImage);

    $firstHalf =  array_slice($splitImage, 0, $count-1);

    $secondHalf = array_slice($splitImage, $count-1);

    $secondHalf[0] = '-' . $width . 'x' . $height . '.' . $secondHalf[0];

    $firstHalfJoined = implode('.', $firstHalf);

    $completedString = $firstHalfJoined . $secondHalf[0];

    // if the filename with the joined string does not exist, return the original image
    if (file_exists($completedString)){
        return $completedString;
    } else {
        return $imagePath;
    }
}

我知道这很粗糙,因此欢迎任何压缩此代码并使其“更好”的想法。我发现该函数始终返回原始图像路径。 file_exists() 可以采用绝对路径(如“http://example.com/image1.jpg”),还是只接受根样式绝对路径(如“/path/to/file/image1.jpg”)?

I've written a function to take an image path, add some text to the end of it, then join it back together. I'm trying to write an if else branch to test if the file exists after I've appended the new text to the image.

For example, if I request the image path:

http://example.com/image1.jpg

It could be modified to this:

http://example.com/image1-150x100.jpg

The function is intended for WordPress, so takes the $post->ID argument, the custom field name, width and height of the intended target.

Here is the function:

function get_galleria_image ( $post_id, $customFieldName, $width, $height ) {

    $imagePath = get_post_meta($post_id, $customFieldName, true);

    $splitImage = explode('.', $imagePath);

    $count = count($splitImage);

    $firstHalf =  array_slice($splitImage, 0, $count-1);

    $secondHalf = array_slice($splitImage, $count-1);

    $secondHalf[0] = '-' . $width . 'x' . $height . '.' . $secondHalf[0];

    $firstHalfJoined = implode('.', $firstHalf);

    $completedString = $firstHalfJoined . $secondHalf[0];

    // if the filename with the joined string does not exist, return the original image
    if (file_exists($completedString)){
        return $completedString;
    } else {
        return $imagePath;
    }
}

I know this is crude, so any ideas to condense this code and make it "better" is welcomed. What I'm finding is that the function always returns the original image path. Can file_exists() take an absolute path like "http://example.com/image1.jpg', or will it only accept a root-style absolute path, like '/path/to/file/image1.jpg'?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不甘平庸 2024-10-22 17:02:31

file_exists 不接受 url 路径。尝试使用 url 路径来检查给定的 url 是否为图像

function isImage($url)
  {
     $params = array('http' => array(
                  'method' => 'HEAD'
               ));
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     if (!$fp) 
        return false;  // Problem with url

    $meta = stream_get_meta_data($fp);
    if ($meta === false)
    {
        fclose($fp);
        return false;  // Problem reading data from url
    }

    $wrapper_data = $meta["wrapper_data"];
    if(is_array($wrapper_data)){
      foreach(array_keys($wrapper_data) as $hh){
          if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19 
          {
            fclose($fp);
            return true;
          }
      }
    }

    fclose($fp);
    return false;
  }

file_exists wont accept url path. Try this for url path to check if the given url is an image or not

function isImage($url)
  {
     $params = array('http' => array(
                  'method' => 'HEAD'
               ));
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     if (!$fp) 
        return false;  // Problem with url

    $meta = stream_get_meta_data($fp);
    if ($meta === false)
    {
        fclose($fp);
        return false;  // Problem reading data from url
    }

    $wrapper_data = $meta["wrapper_data"];
    if(is_array($wrapper_data)){
      foreach(array_keys($wrapper_data) as $hh){
          if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19 
          {
            fclose($fp);
            return true;
          }
      }
    }

    fclose($fp);
    return false;
  }
野生奥特曼 2024-10-22 17:02:31

据我所知,file_exists()仅检查本地文件系统上的文件或目录是否存在。您可能希望通过 fsockopen() 连接到另一台服务器,然后检查 HTTP 代码以查明该文件是否存在。

// you will need to set $host and $file

$sock = fsockopen ( $host );
fwrite ( $sock, "HEAD ".$image." HTTP/1.1\r\n" );
fwrite ( $sock, "Host: ".$file."\r\n" );
fwrite ( $sock, "Connection: close\r\n\r\n" );

// Get the first twelve characters of the response - enough to check the response code
if ( fgets ( $sock, 12 ) == "HTTP/1.1 404" )
    //file doesn't exist
else
    //file exists

fclose ( $sock );

As far as I know, file_exists() only checks if a file or directory on the local file system exits. You may want to connect to another server via fsockopen() and then check the HTTP-Code to find out if the file exists.

// you will need to set $host and $file

$sock = fsockopen ( $host );
fwrite ( $sock, "HEAD ".$image." HTTP/1.1\r\n" );
fwrite ( $sock, "Host: ".$file."\r\n" );
fwrite ( $sock, "Connection: close\r\n\r\n" );

// Get the first twelve characters of the response - enough to check the response code
if ( fgets ( $sock, 12 ) == "HTTP/1.1 404" )
    //file doesn't exist
else
    //file exists

fclose ( $sock );
波浪屿的海角声 2024-10-22 17:02:31

为了使程序的第一部分更加紧凑,您可以执行以下操作:

$completedString = preg_replace("/(.+)\.([^.]+)$/siU", "$1" . "-" . $width ."x" . $height . "$2", $splitImage);

然后使用 @ayush 发布的函数来检查远程服务器上的文件

to make more compact the first part of your procedure you can do something like:

$completedString = preg_replace("/(.+)\.([^.]+)$/siU", "$1" . "-" . $width ."x" . $height . "$2", $splitImage);

then use the function posted from @ayush to check the file on the remote server

落花随流水 2024-10-22 17:02:31
if(@getimagesize($imghttppath))
{
     echo '<img src="'. $imghttppath . '" />';
}
else
{
     echo '<img src="http://www.domain.com/images/default.jpg" />';
}

这是 getimagesize 的一种非正统用法,除非您关闭错误,否则它必须是 @,因为如果文件不存在,它会返回错误。但这是尽可能简单的。使用外部 URL、本地 URL、本地绝对路径和工作目录的相对路径来检查图像是否存在以及是否是实际图像。

if(@getimagesize($imghttppath))
{
     echo '<img src="'. $imghttppath . '" />';
}
else
{
     echo '<img src="http://www.domain.com/images/default.jpg" />';
}

It's kinda an unorthodox use of getimagesize, and it has to be @ unless you turn off errors because it returns an error if the file doesn't exist. But it's about as simple as you can get. Works with External URLs, Local URLs, Local Absolute Paths, and Relative Paths to the working directory to check whether or not an image exists and is an actual image.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文