Home > Back-end >  Catch and handle smarty fetch file not found
Catch and handle smarty fetch file not found

Time:12-10

I have some smarty template code like the below:

{fetch file="https://example.com/file.php" assign='value'}

However, if the URL can't be reached, it 500 error's the page. Error logs reveal "{fetch} cannot read resource".

How would I catch the above to avoid it crashing the page if the URL is unavailable? e.g. if it was a var I could check it with isset to see if it is set but since its a url I don't know how to say "if not found, do this".

Tried the below but no luck.

{if file_exists('https://example.com/file.php')} 
{fetch file="https://example.com/file.php" assign='value'}
{/if}

CodePudding user response:

Need to use smarty function (move this function to smarty function directory):

function smarty_function_checkurl($params)
{
    if (isset($params['url'])) {

        $url      = $params['url'];
        $parsed   = parse_url($url);
        $domain   = str_replace('www.', '', $parsed['host']);
        $response = checkdnsrr($domain);

        if ($response) {

            $file_headers = @get_headers($url);

            if ($file_headers && strpos($file_headers[0], ' 200 OK') !== false) {
                return true;
            }
        }

    }

    return false;
}

and then in .tpl file:

{if {checkurl url="https://example.com/file.php"}}
    YES
    {fetch file="https://example.com/file.php" assign='value'}
{else}
    NOT
{/if}

CodePudding user response:

Let's be honest. The view is not the best place for such things. Suggestion from @r_a_f is all right, but it would be much better to have it in the core of your module.

Then, if you can reach for this external resource, you can pass it to the view along with the other data you need.

You can even use a widget for this: https://devdocs.prestashop.com/1.7/modules/concepts/widgets/

And inside the getWidgetVariables, you can run proper checks.

  • Related