phpfunctionechopageload

PHP echo vs PHP short echo tags


Are they equal in safeness? I was informed that using

<?=$function_here?>

was less safe, and that it slows down page load times. I am strictly biased to using echo.

What are the advantages/disadvantages?


Solution

  • First of all, <?= is not a short open tag, but a shorthand echo, which is the same as <?php echo. And it cannot be disabled. So, it's safe to use in the meaning it is always enabled.

    Speaking of safety in terms of security, the output must be always encoded according the the output medium rules.

    For example, when echoing data inside HTML, it must be HTML-encoded:

     <?= htmlspecialchars($function_here, ENT_QUOTES) ?>
    

    Or, when echoing data inside JavaScript, it must be JavaScript-encoded:

     <script>var=<?= json_encode($function_here) ?>
    

    Or, when it's going to be both HTML and JS, then both encodings must be used:

    <?php foreach($links as $label => $url): ?>
        <br>
        <form method="post">
            <button class="my" onclick="<?=htmlspecialchars("window.open(".json_encode($url).")", ENT_QUOTES) ?>">
                <?=htmlspecialchars($label, ENT_QUOTES) ?>
            </button>
        </form>
    <?php endforeach ?>
    

    Speaking of short open tags, there is only one, <?, and it's not always enabled (see the short_open_tag directive).

    Actually, in the php.ini-production file provided with PHP 5.3.0, they are disabled by default:

    $ grep 'short_open' php.ini-production
    ; short_open_tag
    short_open_tag = Off
    

    So, using them in an application you want to distribute might not be a good idea: your application will not work if they are not enabled.

    <?php, on the other side, cannot be disabled -- so, it's safest to use this one, even if it is longer to write.