Let's say I have some code like this:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die();
}
else{
#Do something
}
?>
</body>
<html>
I hope the purpose of this code is straightforward. If a certain condition is met (ie can't connect to database), then the program should die, but otherwise it should execute. My problem arises when the die() function is executed. It stops right there, and sends only the first three lines to the browser, but not the last two lines.
Is there a funciton that I can use instead of die() so that the php chunks will stop executing, but the static HTML text is still sent through?
One method, which works but is not exactly what I'm looking for, would be to replace
die()
withdie("</body></html>")
. If the text to return were more complicated than that, it could, say, be stored in a variable. Is there anything better than this?Have you looked into using
register_shutdown_function
(php.net) to finish loading the page? It should be able to handledie()
andexit()
.error_page.php
If you're working with PHP4, or just don't want to bother with exceptions, then you could use this technique:
.. though some people seem quite opposed to using this style, appropriately commented, I don't see any issues with it. I'd say it's much better than duplicating your "footer" code in each of your die() statements.
Pass the die a parameter of the static text.
For example change this:
To this:
Decouple your program logic from presentation. Read about MVC, templates.
In simplest form it goes like that:
For other cases, where
die()
or such is unavoidable (e.g. fatal error or 3rd party code dying), there's hack involving output handler:Although I recommend using that only for diagnostic/debugging purposes.