r/PHPhelp • • Jun 06 '25
Question
Hello there!
I would like to ask you something because I've seen many tips and pieces of advice.
Is it better to write PHP code above the HTML code?
I mean like this:
<?php
// PHP code
?>
<!DOCTYPE html>
<!-- HTML code -->
</html>
Thank you for your tips.
4
Upvotes
14
u/allen_jb Jun 06 '25
It's often recommended to put "logic first" before the HTML (view).
In addition to helping to better organize the code, one reason for this is that certain operations - specifically anything that affects the response headers (
header(), including redirects, or anything that works with cookies, including session initiation) - must be done before (other) output starts (except when using output buffering).If you're currently writing simple, single-file scripts, this also makes it easier to migrate them, as the project grows, to "MVC style", moving the logic into controllers, and data storage into the (database) "models" (repositories). A very similar concept is "Action Domain Responder"
4
u/Big-Dragonfly-3700 Jun 06 '25
The code for any page should be laid out in this general order -
4
u/AshleyJSheridan Jun 06 '25
It's generally better to not mix HTML and PHP at all if you can help it, and instead look at using a templating system.
However, if you are mixing the two, then these are some things to consider:
Content-Type: text/htmlheader unless you specify a different one). Some functionality in PHP (like session handling) has to happen before any headers are sent, and headers are automatically sent as soon as any output is sent to the browser.2
u/abrahamguo Jun 06 '25
It just depends on whether you want to run your code before printing the HTML, or not.
2
u/greg8872 Jun 06 '25 edited Jun 07 '25
Another reason for doing this is debugging. When you are trying to debug something, you can easily use var_dump()'s and die() after it to see items at that point and stop. When you have your logic mingled in within the output, doing the same is going to put that debug information after partial output of the page.
Sometimes, that output could be in a place where it is not rendered on the screen to fully see it, and force you to do View->Source to see it. When all the processing is first, it is the first output.
Also, the same goes for warnings/noticed that may appear, this ensures they are all at the top of of the output (though, IMO, you should be sending them all to log file, and tail the log file while developing so you can see them pop up. I keep it and console log for browser open on secondary monitor, so as you are working on the site, out of the corner of your eye you can see something scroll when it happens.)
1
u/Mastodont_XXX Jun 07 '25
Yoou should use at least TWO files. First is PHP file where you prepare data into variables and then include template file. Second file is HTML template with embedded PHP echoes.