Why the PHP function fopen() and related variable behave differently in smarty templating engine?

80 views Asked by At

Consider the snippet code:

{if $showfile eq 'debug'}
    <pre>{php}
        if ( $fh = fopen('../logs/debug.log' , "r") ) {
            readfile('../logs/debug.log'); 
            fclose($fh);
        } else {
            echo "Error: debug file can not be read.";
        }
    {/php}</pre>
{/if}

Output the content in debug.log file but the below code:

{if $showfile eq 'debug'}
    <pre>{php}
        if ( $fh = fopen('../logs/'.$showfile.'.log' , "r") ) {
            readfile('../logs/'.$showfile.'.log'); 
            fclose($fh);
        } else {
            echo "Error: ".$showfile." file can not be read.";
        }
    {/php}</pre>
{/if}

showing me the following output:

Error:  file can not be read.

What is the problem? Why the $showfile variable become empty after the {if $showfile eq 'debug'} condition ...

1

There are 1 answers

0
Rob Ruchte On

The {php} tags in Smarty have their own scope, like a PHP function. If you want to use the $showfile variable, you need to use the global keyword.

{php}
    global $showfile;
{/php}