PHP - exit or die() in AJAX requests? - php

What's the best practice here? Using die() or exit()? What's the difference between the two?
if($_GET['do_thing']):
echo 'bla bla';
exit(); // or die(), or something else?
endif;

die('bla bla');, echo 'bla bla';exit(); and exit('bla bla'); do the same thing. Personally, I use die only for debugging code, and an empty exit for regular termination - as in your case. However, die and exit are synonyms, so it does not matter which one you use.

I use die() when making mysql queries to log the errors, I use exit to bail out of loops.

I prefer die, but for no particular reason. PHP Docs say that exit is the real language construct (http://www.php.net/manual/en/function.exit.php) and die is simply an alias, but both work.
It just depends on your coding style and choice of grammar!

Related

PHP - Is danger to use mysqli connect without die() when connect error? [duplicate]

If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.

Better way than die() [duplicate]

If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.

mysqli or die, does it have to die?

If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.

Why if/else vs. or/exit in PHP?

Seeing the exit() PHP documentation got me thinking:
$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
or exit("unable to open file ($filename)");
Couple questions:
What are common use cases besides opening files for using exit()?
Since not every function everyone ever writes ends in exit(), how do you know to use it in some contexts vs. others?
Are if/else and or/exit interchangeable?
In that context, the or in that statement is one of PHP's logical operators which when used like that, will execute the second statement if and only if the first one fails due to short circuit evaluation.
Since fopen returned false, the or exit statement gets executed since the first part failed.
To understand it better, here is a quick explanation of short-circuit evaluation.
$x = 5;
$y = 42;
if ($x == 5 or $y == 42) {
echo "x or y is true";
}
In the above code, the expression $y == 42 is never evaluated because there is no need since the first expression was true.
In that example, they are using the same logic for deciding whether or not to evaluate the statement that calls exit.
To address your questions:
I wouldn't use exit when opening a file failed unless the program was very specific. The better thing to do would be to log an error and then return the error to the caller so they can decide what to do.
When to use exit completely depends on the code you are writing.
Given the explanation about short-circuiting, yes they are interchangeable in that sense. Using or exit is just a bit shorter than using if/else.
Hope that helps.
CLI scripts, exit can take an integer parameter which is fed back to the console to indicate success or some form of error
I'm not inclined to use exit() or die() in application code, since exceptions are preferred. However, I personally think you might be overcomplicating things a little bit... it kills script execution, so use it when you need to kill a script. Truthfully I mostly only ever kill scripts mid-execution when debugging (one-off breakpoints) and that's not ideal either (again exceptions do a better job).
The use of or is mostly convenient. Here's an interesting point though...
Why does
$resource = mysql_connect() || die('dead')
not work?
The answer is that the = operator takes precedence over or so that the assignment is made first like so: ($resource = mysql_connect()) or die(). In this way its exactly like doing an if(!($resource = mysql_connnect())) { die() }
I tend to avoid using exit() at all as it's a really ugly way to handle errors from the user's perspective.
If you must use it, any non recoverable error would be a candidate. For example, database query or connection failures, or remote request failures.
if/else is equivalent to ...or whatever(). It's just a style thing, with the latter form being more succinct.
I would say you use exit in a situation where your code cannot continue if the function you were doing failed. For example reading a file that is needed.

What is the difference between echo('exit'); die; and die('exit');?

I have seen some code do this:
if(something){
echo 'exit from program';
die;
}
...more code
And others that just use die:
if(something) die('exit from program');
...more code
Is there any inherent difference in when it would end the program, should I be aware of the code that comes after it? etcetera
UPDATE
I am asking mainly, if it is a coding style, or if there is a real reason why some is coded one way versus another. I am not asking what the difference between exit and die is.
No, there is no difference; they will both write "exit" to STDOUT and terminate the program.
I would prefer the die("exit") method as it's less typing, easier to comment out and semantically clearer.
As far as "speed", why would you care which is faster? Do you need your program to die really quickly?
RE: Your update
... any inherent difference in when it would end the program ...
There is no difference, inherent or otherwise. They're identical. The second option, die('exit'), is a single statement, and so requires no braces when used with an if statement; this has nothing to do with the die and everything to do with blocks and flow control in C-style languages.
RE: Your comment/second update
Which way you die is a matter of personal preference. As I said, they are identical. I would choose the 2nd option for the reasons listed above: Shorter, clearer, cleaner, which amounts to "better" in my opinion.
The difference between exit and die is that exit allows you to return a non-zero status, while die returns 0. Neither function is "better", they serve different purposes.
no difference.
And why asking for speed difference since you're dieing.
There IS a difference guys. DIE() can be used with other failable functions whereas echoing would need to caught as an error or exception.
$query = mysql_query("SELECT * FROM tablename") OR DIE(mysql_error());
Gives you an immediate catch/die sequence.
For the specific example you posted they are equal, since the $status is a string, but as the manual says this may not always be the case:
If status is a string, this function
prints the status just before exiting.
If status is an integer, that value
will be used as the exit status and
not printed. Exit statuses should be
in the range 0 to 254, the exit status
255 is reserved by PHP and shall not
be used. The status 0 is used to
terminate the program successfully.
So if instead of 'exit from program' you wanted to output, say 42 you would really need to do:
echo 42; die();
The language constructs exit() and die() are equivalent, at least according to the PHP manual. I use exit() when that line should be reached and I want the script to stop at that point. Die() on the other hand is for situations that should not occur. That's just what feels most natural for me, you don't have to agree.
Mostly it's coding style. However, if you are outputting debug messages, echo then die is better:
echo "The frobnuticator blew up!";
die;
becomes
//echo "The frobnusticator blew up!";
die;
Of course, you'd most likely have
if ($debug) echo "The frobnusticator blew up!";
die;
Which is much easier on (my|the) eye than
die($debug?"The frobnusticator blew up!":"");
From php manual :
Note: This language construct is equivalent to die().
But still there are difference between die and exit :
Using die() you can post a string : die("An error occurred");
Same result with using exit()
<?php
echo("An error occurred <br>");
exit(0);
?>
OR if you are cli or unix shell :
Using PHP on the command line, die("An error occurred") simply prints "An error occurred" to STDOUT and terminates the program with a normal exit code of 0.
<?php
fwrite(STDERR, "An error occurred \n");
exit(0); //
?>

Categories