I am new to php and wonder what am I missing about the rules for interleaving html and php code.
This is now the second time I run into a situation where a php file only works if my php tag is at the beginning of the file. This is not the case for all my files. I wonder why that might be.
Here is an example:
My file structured as follows works just fine:
<?php
... my php code
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Authentication</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="container">
</div>
</body>
</html>
But when I move that html block at the top (which is what I want ultimately since I use some echo statements in my php code), and leave only the following at the bottom:
</div>
</body>
</html>
then some portion of the php code do not work. For example, my setcookie function no longer sets a cookie (though it does not error out) while I can still run sql queries or echo statements just fine. I ran into a similar issue with a complete different code taken straight out of a tutorial site: the example would only work if the code started with
Some operations (like writing a cookie) must be performed by PHP before any output is sent to the browser, because those operations involve setting response headers (which are always sent before any other content). That seems to be the problem here.