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

PhpSyntaxParse Error

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

In PHP, you can use the script tag to open a PHP block.

So you can use

<script language="php">
    echo 'hello world';
</script>

So in your example you have mixed the normal open tag, <?php, with the closing tag, </script>. So the parser assumes that all the text after the closing script tag is normal HTML.

Read more in Escaping from HTML.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIrfanView Question on Stackoverflow
Solution 1 - PhpPekkaView Answer on Stackoverflow
Solution 2 - PhpamdView Answer on Stackoverflow