PHP: Error handling with include - php

$file= #fopen("ssssss.php", r) or die("not found");
(#include("ssssss.php")) or die("not found");
In the first statement we don't put ( ) around #fopen and it is working fine.
But in the second if I didn't put these () it does't show any message.
so why with include I must round it with ( ) ?

I agree with the suggestions in the other answers but the actual answer to your question is this:
In the PHP documentation they say to take care when comparing the return value of include.
That's because it is a special construct and parentheses are not needed.
So when you do this (without wrapping parentheses):
#include("ssssss.php") or die("not found");
You're actually doing this, because or is evaluated first:
#include (("ssssss.php") or die("not found"));
Now, "ssssss.php" is a non empty string that evaluates logically to true.
or is a logical operator that gives true if any of the parameters is true (or both of them).
Also, this operator is short-circuit: if the first parameter is true, php already knows that the operator or will return true, so it doesn't waste time evaluating the second parameter, and die() is not executed.
So finally, or gives true and your sentence becames this:
#include (1);
Php tries to "include 1", and it would raise a warning but it does not because of the #.
Here you have a similar example in php.net.
Your first sentence is not the same case.
$file= #fopen("ssssss.php", r) or die("not found");
fopen is just a regular Php's function with its parentheses. Here you need to have in mind two operators: = and or.
= has higher precedence than or, so, if fopen's result is correctly assigned to $file (and it is), that operation will return true. And, as I explained before, "true or anything else", gives true but die() is not executed because of the short-circuit operator.

You should be using file_exists instead of using the # as the later covers all sorts of issues. A better solution would be...
if (file_exists("ssssss.php")) {
$file= #fopen("ssssss.php", r);
}
and
if (file_exists("ssssss.php")) {
include("ssssss.php");
}

That's not really a good use of include. If you need to include a php file and generate an error on failure, use require or require_once.
If you need to get the contents of the whole file, you could use file_get_contents().
Also, I agree with Nigel Ren about the use of # - it is a dangerous practice and should be avoided.

Related

Why can't the php interpreter not parse unset call after &&? [duplicate]

I've just read the page on Expressions in the PHP docs, and right at the top it says:
The simplest yet most accurate way to define an expression is "anything that has a value".
That simple definition includes all functions and most language constructs, however there a few language constructs that explicitly state they do not return a value.
Here is a list of language constructs that do return a value:
empty
eval
include
include_once
isset
list
require
require_once
print
Here are the interesting few which do not return a value, and therefore are not expressions:
die
echo
exit
return
unset
__halt_compiler
I find die and exit of particular interest, because they can be used as expressions in PHP despite having no return values. The following lines of code all throw a syntax error, as expected:
echo 'Hi' or echo 'Bye';
if(echo('foo'))
return return(1);
$foo['bar'] = isset($foo['bar']) ? unset($foo['bar']) : 0;
if(unset($foo['bar']))
__halt_compiler() or die;
However the following PHP code is completely free of syntax errors:
print 'Hi' or print 'Bye'; // Makes sense, print returns a value
if(!die() and exit) // Wait what's happening here?
quit(die(exit(quit()))); // die and exit don't have return values (does quit?)
$x = true ? die/2 : 5*exit();
$y = pow(die,7);
isset($_GET['bar']) or die(); // This one is actually pretty commonly used.
function quit(){
return exit;
}
I've looked through the PHP docs and can't find any mention of this special treatment of die() and exit(). Do any PHP experts know if this is documented anywhere. Is this intended behaviour, and is the isset($_GET['bar']) or die(); pattern safe to use; could it suddenly break in a future version of PHP?
PHP does not detect errors except at run time when the code path is reached. Unlike many other languages, it does not list the errors when the page is "compiled" - so you'll only see errors as their respective lines of source code are executed.
In your example, the evaluation of the return value of exit or die is never done. PHP doesn't report an error because it never tried to evaluate the result in the first place, because the thread exited.
die and exit (they share the T_EXIT token) fall under the rules for expr_without_variable during the parsing phase, which is why PHP is happy to have them in an expression context without giving a syntax error.
Do any PHP experts know if this is documented anywhere.
There is no description of the special treatment in the PHP manual, however the first example on the exit manual page shows it being used as … or exit.
Is this intended behaviour, and is the isset($_GET['bar']) or die(); pattern safe to use; could it suddenly break in a future version of PHP?
Yes. Yes. Anything's possible, however unlikely.
A wild guess is that die and exit do return a value, however, it will never be returned since the execution is halted before it is returned.
This might have been implemented in order to add some "usefulness" to the die and exit functions.
die and exit return value, however that value have to be used by the program that has called the PHP script. This comment describes the behavior.

What does "or" do in the context of errors?

Reading this question I want to copy #Your Common Sense's error checking when using mysqli
$query="INSERT INTO testtable VALUES (23,44,56)";
$stmt_test->prepare($query);
$stmt_test->execute() or trigger_error($stmt_test->error);
$stmt_test->close();
How does or work? Another example of it's use is
$fh = fopen($myFile, 'w') or die("can't open file");
How is it different than using an if statment and would should it be used instead?
If the first statement returns false, then the second one is executed. That's it.
This is often how boolean "or" expressions are evaluated in programming languages. If you have a statement involving functions thus:
if (a() or b()) { ... }
then PHP works out that, if a() returns true, there is no need to evaluate the second function, since the overall result will be true regardless of the outcome of the second part. We can use this trick as a simple if mechanism:
(operation_that_might_fail() or report_error());
Here, I've removed the if around the clause. This will be evaluated just as before - except the result of ORing the two is then thrown away, since we don't need to do anything with it.
For this to work, operation_that_might_fail() must return boolean true on success, and false otherwise. As it happens, many PHP functions do exactly that, so we can often use this approach.
Side note: whilst the statement or is arguably clearer, PHP programmers tend to prefer the operator ||. Similarly, and will do what it says, but && is more common.

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.

Is this special treatment of exit and die documented in PHP?

I've just read the page on Expressions in the PHP docs, and right at the top it says:
The simplest yet most accurate way to define an expression is "anything that has a value".
That simple definition includes all functions and most language constructs, however there a few language constructs that explicitly state they do not return a value.
Here is a list of language constructs that do return a value:
empty
eval
include
include_once
isset
list
require
require_once
print
Here are the interesting few which do not return a value, and therefore are not expressions:
die
echo
exit
return
unset
__halt_compiler
I find die and exit of particular interest, because they can be used as expressions in PHP despite having no return values. The following lines of code all throw a syntax error, as expected:
echo 'Hi' or echo 'Bye';
if(echo('foo'))
return return(1);
$foo['bar'] = isset($foo['bar']) ? unset($foo['bar']) : 0;
if(unset($foo['bar']))
__halt_compiler() or die;
However the following PHP code is completely free of syntax errors:
print 'Hi' or print 'Bye'; // Makes sense, print returns a value
if(!die() and exit) // Wait what's happening here?
quit(die(exit(quit()))); // die and exit don't have return values (does quit?)
$x = true ? die/2 : 5*exit();
$y = pow(die,7);
isset($_GET['bar']) or die(); // This one is actually pretty commonly used.
function quit(){
return exit;
}
I've looked through the PHP docs and can't find any mention of this special treatment of die() and exit(). Do any PHP experts know if this is documented anywhere. Is this intended behaviour, and is the isset($_GET['bar']) or die(); pattern safe to use; could it suddenly break in a future version of PHP?
PHP does not detect errors except at run time when the code path is reached. Unlike many other languages, it does not list the errors when the page is "compiled" - so you'll only see errors as their respective lines of source code are executed.
In your example, the evaluation of the return value of exit or die is never done. PHP doesn't report an error because it never tried to evaluate the result in the first place, because the thread exited.
die and exit (they share the T_EXIT token) fall under the rules for expr_without_variable during the parsing phase, which is why PHP is happy to have them in an expression context without giving a syntax error.
Do any PHP experts know if this is documented anywhere.
There is no description of the special treatment in the PHP manual, however the first example on the exit manual page shows it being used as … or exit.
Is this intended behaviour, and is the isset($_GET['bar']) or die(); pattern safe to use; could it suddenly break in a future version of PHP?
Yes. Yes. Anything's possible, however unlikely.
A wild guess is that die and exit do return a value, however, it will never be returned since the execution is halted before it is returned.
This might have been implemented in order to add some "usefulness" to the die and exit functions.
die and exit return value, however that value have to be used by the program that has called the PHP script. This comment describes the behavior.

What does "or" in php mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP - and / or keywords
I saw several bits of PHP code using or in a way I was unfamiliar with. For example:
fopen($site,"r") or die("Unable to connect to $site");
Is this equal to this ||?
Why would you use this instead of a try catch block? What will cause the program run the or die()?
It is for the most part, but...
The reason for the two different
variations of "and" and "or" operators
is that they operate at different
precedences.
See http://php.net/manual/en/language.operators.logical.php
or is equal to || except that || has a higher presedense than or.
Reference:
http://www.php.net/manual/en/language.operators.precedence.php
or has an other precedence. The concrete statement is little trick with boolean operators. Like in a common if-test-expression the second part is only executed, if the first is evaluated to false. This means, if fopen() does not fail, die() is not touched at all.
However, try-catch only works with Exceptions, but fopen() doesnt throw any.
Today something like this is "not so good" style. Use exceptions instead of hard abortion
if (!($res = fopen($site, 'r'))) throw new Exception ("Reading of $site failed");
or die happens with the first command fails.
It is similar to a try catch, but this is more direct approach.
Note that this is a classical test:
fopen($site,"r") or die("Unable to connect to $site");
Only if fopen($site,"r") returns false, will the second half of the test be run: 'die('error')'.
Same is if(a || b); b is only run if a returns false.
Die in PHP is the same as exit();
http://www.php.net/manual/en/function.exit.php
Stops execution of the current script entirely, and prints out the error message.
Yes it equals ||
In this case it is explicitly stopping the execution of the page and printing that error message.

Categories