简体   繁体   English

如何使用 URL 检查 smarty 上是否存在图像文件?

[英]How can i check if image file exists on smarty using URL?

I want to check if the webp image is exists on the server on smarty .我想检查smarty上的服务器上是否存在 webp 图像。 The URL is an absolute URL like this . URL这样的绝对URL

i tried我试过了

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

and

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

{/if}

But none is working.但没有一个在工作。 Can anyone tell me how to do this?谁能告诉我该怎么做?

In your controller, you should do something like:在您的控制器中,您应该执行以下操作:

if (file_exists($filename))

You could also do this in the view as you're trying to do now, but it's recommended to keep your logic separated from your view.您也可以像现在一样在视图中执行此操作,但建议将逻辑与视图分开。

Don't forget to add the absolute path to the $filename variable.不要忘记将绝对路径添加到$filename变量。

Edit :编辑

In case of smarty, you can do the following in your php script:在 smarty 的情况下,您可以在 php 脚本中执行以下操作:

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

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

In the view/template, you can then simply do:在视图/模板中,您可以简单地执行以下操作:

{if $fileExists}

In smarty, you cannot use file_exists() on a URL, but you can use it on a local file在 smarty 中,您不能在 URL 上使用file_exists() ,但可以在本地文件上使用它

I think, the best way is to check in your controller.我认为,最好的方法是检查您的控制器。

1st method:第一种方法:

In your controller, you can write something like that (path only): https://www.php.net/manual/fr/function.file-exists.php在您的控制器中,您可以编写类似的内容(仅限路径): 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'

Then return the variable $filename然后返回变量$filename

Other way :另一种方式 :

If you want to check that the image exists from a URL then you should use this:如果要检查 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;
}

then //do something...然后//do something...

You Have To Check File IN file_exists("var/www/html/example.com/image.webp") it will note Check Http or Https您必须在 file_exists("var/www/html/example.com/image.webp") 中检查文件,它会提示检查 Http 或 Https

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM