I'm trying to add some error checking inside my PHP script. Is it valid to do this:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
echo json_encode($res);
die;
}
Is there a better way to exit the script after encountering an error like this?
What is the difference between echo and die() or are they same? The die() function can accept an optional argument string that it will output just before terminating the script. echo() only outputs its arguments, it will not terminate the script.
Echo simply outputs the strings that it is given, if viewing in the browser it will output the strings to the browser, if it's through command line then it will output the strings to the command line.
die() function in PHP The die() function prints a message and exits the current script.
That looks fine to me.
You can even echo data in the die
like so:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
die(json_encode($res));
}
Throwing a exception. Put code into a try catch block, and throw exception when you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With