phpsmartysmarty3smarty2

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. The URL is an absolute URL like this.

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?


Solution

  • 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.

    Edit:

    In case of smarty, you can do the following in your php script:

        $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}