【问题标题】:use file_exists() to check wordpress uploads folder使用 file_exists() 检查 wordpress 上传文件夹
【发布时间】:2015-03-08 01:04:38
【问题描述】:

我在 Wordpress 上传文件夹中创建了一个目录,供最终用户通过 ftp 批量上传照片。图像编号为 1.jpg、2.jpg... 等。我已经成功生成了图像 url,但现在我想测试空 url - 即如果“8.jpg”不存在,则显示占位符图像而是从主题的图像文件夹中。

我正在尝试使用 file_exists(),但这每次都返回 false 并且始终显示占位符图像。任何建议将不胜感激。

<?php while ( have_posts() ) : the_post();
    // create url to image in wordpress 'uploads/catalogue_images/$sale' folder
    $upload_dir = wp_upload_dir();                          
    $sub_dir = $wp_query->queried_object;
    $image = get_field('file_number');
    $image_url = $upload_dir['baseurl'] . "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG"; ?>

    <?php if(file_exists($image_url)){
        echo '<img src="' . $image_url . '" alt="" />';
    } else {
        //placeholder
        echo '<img src="' . get_bloginfo("template_url") . '/images/photo_unavailable.jpg" alt="" />';
    } ?>                                
<?php endwhile; ?>

【问题讨论】:

  • file_exists 需要一个内部文件路径,而不是 HTTP 路径。
  • file_exists 需要服务器上图像的路径,而不是相对于文档根目录的 URL。 $image_url的变量内容是怎样的?

标签: php wordpress file-exists


【解决方案1】:

PHP的file_exists函数主要是expects an internal server path to the file to be testedexample 让这一点显而易见。

幸运的是,我们看到wp_upload_dir() 为我们提供了几个有用的值:

  • 'path' - 基本目录和子目录或上传目录的完整路径。
  • 'url' - 基本 url 和子目录或上传目录的绝对 URL。
  • 'subdir' - 子目录,如果上传使用年/月文件夹选项打开。
  • 'basedir' - 没有子目录的路径。
  • 'baseurl' - 没有子目录的 URL 路径。
  • 'error' - 设置为 false。

我已经用粗体显示了我们想要使用的内容。使用这两个值,您必须生成两个变量,一个用于外部 URL,一个用于内部文件路径:

$image_relative_path = "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG";
$image_path = $upload_dir['basedir'] . $image_relative_path;
$image_url = $upload_dir['baseurl'] . $image_relative_path;

然后使用file_exists($image_path) 而不是file_exists($image_url)

注意

与 PHP >= 5.0.0 上的 PHP 注释一样,您 can indeed use file_exists with some URLs,但 http:// 协议是 not supported for the stat() function(这是 file_exists 使用的。)

【讨论】:

  • 工作 - 非常感谢您清楚地解释它。
【解决方案2】:

您必须使用内部路径来检查文件是否存在。 所以用$upload_dir['path']代替$upload_dir['baseurl']

[path] - 上传的基目录和子目录或完整路径 目录。

http://codex.wordpress.org/Function_Reference/wp_upload_dir

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2015-06-06
    • 2013-11-30
    • 2015-01-07
    • 2019-04-11
    相关资源
    最近更新 更多