1

我想检查 webp 图像是否存在于smarty. URL绝对URL这样的。

我试过了

{if file_exists("https://example.com/image.webp")}
{/if}

{if 'https://example.com/image.webp'}

{/if}

但没有一个工作。谁能告诉我该怎么做?

4

2 回答 2

1

在您的控制器中,您应该执行以下操作:

if (file_exists($filename))

您也可以像现在尝试那样在视图中执行此操作,但建议您将逻辑与视图分开。

不要忘记将绝对路径添加到$filename变量中。

编辑

在 smarty 的情况下,您可以在 php 脚本中执行以下操作:

    $smarty = new Smarty();
    
    $fileExist = false;
    if (file_exists($filename)) {
      $fileExists = true;
    }

    $smarty->assign('fileExists', $fileExists);
    
    $smarty->display('index.tpl');

在视图/模板中,您可以简单地执行以下操作:

{if $fileExists}
于 2020-09-08T13:12:14.750 回答
0

在 smarty 中,不能file_exists()在 URL 上使用,但可以在本地文件上使用

我认为,最好的方法是检查你的控制器。

第一种方法:

在您的控制器中,您可以编写类似的内容(仅限路径): https ://www.php.net/manual/fr/function.file-exists.php

$filename = '/example.com/image.webp'
if(!file_exist($filename))
    $filename = '/example.com/other_image.webp'

然后返回变量$filename

另一种方式 :

如果您想检查来自 URL 的图像是否存在,那么您应该使用以下命令:

$file = 'http://www.example.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

然后//do something...

于 2020-09-08T13:13:57.893 回答