Thursday, May 10, 2012

Can I call die after echo with PHP?


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?


Source: Tips4all

3 comments:

  1. 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));
    }

    ReplyDelete
  2. Throwing a exception. Put code into a try catch block, and throw exception when you need.

    ReplyDelete
  3. PHP has functions for error triggering and handling.

    if (!mkdir($dir, 0)) {
    trigger_error('Failed to create directory', E_USER_ERROR)
    }


    When you do this the script will end. The message will be written to the configured error log and it will also be displayed when error_reporting is enabled.

    ReplyDelete