Skip to main content

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: Tips4allCCNA FINAL EXAM

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

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?