193

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Irfan
  • 7,029
  • 3
  • 42
  • 57
  • Just curious. What were trying to achieve or what was it that you were experimenting on? – asprin Nov 05 '12 at 08:22
  • 8
    Actually the case was different last night I missed the php closing tag.And after this I had a tag and I spent more than 30 min to figure out why this does not have any error buts still the output is not as desire. – Irfan Nov 05 '12 at 08:25
  • 7
    I don't want to live on this planet any more. – Kzqai May 06 '13 at 16:48
  • 2
    PHP does that to people. – xiankai Sep 29 '13 at 11:12

2 Answers2

273

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
Giulio Muscarello
  • 1,312
  • 2
  • 12
  • 33
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
37

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
amd
  • 20,637
  • 6
  • 49
  • 67