php - 使用 file_exists() 检查 WordPress 上传文件夹

标签 php wordpress file-exists

我在 WordPress 上传文件夹中创建了一个目录,供最终用户通过 ftp 批量上传照片。图像编号为 1.jpg、2.jpg...等。我已成功生成图像网址,但现在我想测试空网址 - 即如果“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; ?>

最佳答案

PHP file_exists 函数主要 expects an internal server path to the file to be tested 。这通过example变得显而易见。 .

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

  • 'path' - base directory and sub directory or full path to upload directory.
  • 'url' - base url and sub directory or absolute URL to upload directory.
  • 'subdir' - sub directory if uploads use year/month folders option is on.
  • 'basedir' - path without subdir.
  • 'baseurl' - URL path without subdir.
  • 'error' - set to 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:// 协议(protocol)是 not supported for the stat() function (这是 file_exists 使用的。)

关于php - 使用 file_exists() 检查 WordPress 上传文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865151/

相关文章:

php - 有没有办法测试闭包是否也是生成器?

c++ - 如何检查文件是否存在于目录中?

php - 如何创建包含上传图像的 Slack 消息?

php - 选择 MySQL 行而不考虑列的数据

javascript - 多列网格中,如何限制每列的元素数

php - 使用 if/else 选择 php 输出源

php - Wordpress 静态页面 'SEO' ?

php - 以正确的方式制作自定义 WordPress 页面

如果存在,PHP重命名文件名将数字附加到结尾

c - 当文件实际存在时 open() 文件不存在