Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call die after echo with PHP?

Tags:

json

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?

like image 754
Paul Avatar asked Nov 17 '11 18:11

Paul


People also ask

What is the difference between die and echo in PHP?

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.

Where does PHP echo output go?

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.

What does die () do in PHP?

die() function in PHP The die() function prints a message and exits the current script.


2 Answers

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));
}
like image 192
Naftali Avatar answered Sep 20 '22 18:09

Naftali


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

like image 44
Hamikzo Avatar answered Sep 22 '22 18:09

Hamikzo