PHP: error handling with include

$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 works fine. But in the second case, if I didn't put these (), it won't show any messages.

so why include include, should I combine it with ()?

+3


source to share


3 answers


I agree with the suggestions in other answers, but the actual answer to your question is this:

In the PHP documentation, they say to be careful when comparing the return value of the include.

This is because this is a special construct and no parentheses are needed.

So when you do this (no parentheses):

@include("ssssss.php") or die("not found");

      

You are actually doing this because it evaluates first or

:

@include (("ssssss.php") or die("not found"));

      

Now "ssssss.php" is a non-empty string that logically evaluates to true.

or

is a boolean operator that evaluates to true if either of the parameters is true (or both). Also, this operator is short-circuited: 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 is die()

not executed.



So, or

gives true and your suggestion becomes this:

@include (1);

      

Php is trying to "include 1" and it will raise a warning, but it doesn't @

.

You have a similar example here at 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 function with its parentheses. There are two operators to keep in mind here: =

and or

.

=

has higher precedence than or

, so if the result of fopen is correctly assigned $file

(and it is), this operation will return true. And, as I explained earlier, "true or

anything else" gives true, but die () is not executed due to the short-circuit statement.

+2


source


You should use file_exists

instead of using @

as the latter will cover all kinds of problems. The best solution would be ...

if (file_exists("ssssss.php")) {   
    $file= @fopen("ssssss.php", r);                       
}

      



and

if (file_exists("ssssss.php")) {   
   include("ssssss.php");                       
}

      

0


source


This is not a good use of include. If you need to include a php file and generate a crash error, use require

or require_once

.

If you need to get the contents of the entire file, you can use file_get_contents()

.

Also, I agree with Nigel Wren @

that it is a dangerous practice to use and should be avoided.

0


source







All Articles