Search code examples
phpsyntaxparse-error

In PHP, why does </script> not show a parse error?


I was running the following PHP code:

<?php 
    </script>
?>

There were no parse errors and the output was "?>" (example).

In similar cases I do get a parse error:

<?php 
    </div>
?>

Parse error: syntax error, unexpected '<' in ...

Why doesn't <?php </script> ?> give the same error?


Solution

  • This must be because there are various ways of starting a block of PHP code:

    • <? ... ?> (known as short_open_tag)

    • <?php ... ?> (the standard really)

    • <script language="php"> ... </script> (not recommended)

    • <% ... %> (deprecated and removed ASP-style tag after 5.3.0)

    Apparently, you can open a PHP block one way, and close it the other. Didn't know that.

    So in your code, you opened the block using <? but PHP recognizes </script> as the closer. What happened was:

    <?php       <----- START PHP
    </script>   <----- END PHP
    ?>          <----- JUST GARBAGE IN THE HTML