【问题标题】:CakePHP 3: How to check if file or image existsCakePHP 3:如何检查文件或图像是否存在
【发布时间】:2015-11-18 06:22:17
【问题描述】:

我只是想检查图像是否存在,我可以使用 PHP 来完成。例如:-

$file = WWW_ROOT .'uploads' . DS . 'employee' . DS .'_'.check.jpg;

$file_exists = file_exists($file);

它对我来说很好用。但我也试过像这样使用elementExists:-

if($this->elementExists("../".$employees->front_image))
{
   echo $this->Html->image("../".$employees->front_image); // image output fine without condition.
}

// Here $employees->front_image = uploads/employee/employeename.jpg

此检查不起作用。我怎样才能在 CakePHP 中做到这一点?

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    CakePHP 是用 PHP 编写的,所以如果您已经有像 file_exists() 这样的简单解决方案,请使用它。所以你可以这样写:-

    if (file_exists(WWW_ROOT . $employees->front_image)):
       echo $this->Html->image('../' . $employees->front_image);
    endif;
    

    elementExists() 用于检查 View 元素是否存在,而不是 webroot 中是否存在文件,因此不应像您尝试的那样使用。它确实会进行file_exists() 检查,但这只会扫描所有可用的视图元素路径。

    【讨论】:

    • 我可以通过 file_exists() 解决它。我的问题是 cakephp 有什么方法可以做同样的事情吗?
    • 我不知道。您正在尝试做的是一个非常简单的检查,并且 CakePHP 提供的任何替代方法都可能是矫枉过正的,因为您只是调用一个最终将调用 file_exists() 的包装函数。如果您查看elementExists() 的代码,您会发现Cake 使用file_exists() 本身来检查文件是否存在。您大概知道您的图像文件将存在于哪个目录(如果存在),因此最好的解决方案(也是性能最佳的)将是直接调用file_exists()
    【解决方案2】:

    我认为这适用于 Cake 3(你应该在 afterFind 方法 IMO 中这样做):

    // Create a new file with 0644 permissions
    $file = new File('/path/to/file.php', true, 0644);
    
    if ($file->exists()) {
        //do something
    }
    
    $file->close();
    

    你的方法是检查视图元素是否存在。

    【讨论】:

      【解决方案3】:

      这对我有用:

      问:如何检查远程网址上是否存在图片? 说明:

      • $rfile 将获取 url
      • $check 将以读取权限打开文件
      • 如果文件存在,则打印“文件存在”,否则打印“不存在”。

      代码:

      <?php
        // Remote file url
        $rFile = 'https://www.example.com/files/test.pdf';
      
        // Open the file
        $check = @fopen($rFile, 'r');
      
        // Check if the file exists
        if(!$check){
          echo 'File does not exist';
        }else{
          echo 'File exists';
        }
      ?>
      

      【讨论】:

      猜你喜欢
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      相关资源
      最近更新 更多