Note: I am using output buffering. It’s just wrapped in the head() and foot() functions.
I create pages in my current PHP project by using the following template:
<?php
include 'bootstrap.php';
head();
?>
<!-- Page content here -->
<?php
foot();
?>
Is the following example an appropriate use of die()? Also, what sort of problems might this cause for me, if any?
<?php
include 'bootstrap.php';
head();
try
{
//Simulate throwing an exception from some class
throw new Exception('Something went wrong!');
}
catch(Exception $e)
{
?>
<p>Please fix the following error:</p>
<p><?php echo $e->getMessage(); ?></p>
<?php
foot();
die();
}
//If no exception is thrown above, continue script
doSomething();
doSomeOtherThing();
foot();
?>
Basically, I have a script with multiple tasks on it and I am trying to set up a graceful way to notify the user of input errors while preventing the remaining portion of the script from executing.
Thanks!
The whole page structure is wrong.
Though it’s most widespread newbie mistake.
One should never output a thing before having all data ready.
Your script may send some HTTP headers, may set up some variables for use in the header() or anything.
Therefore, template use is necessary.
You have to divide your script into 2 parts – getting data part and displaying data part.
So, you have to move header() function much lower.
And based on the Amadan’s answer it could be
handleError() function may set appropriate HTTP error code (404 or 500) and substitute body template with error message text.