PHP Warning when using include_once()-ThrowExceptions

Exception or error:

When I try to include a file using include_once in php which shows warning like

Warning: include_once(1) [function.include-once]: failed to open stream: No such file or directory in /var/www/test/content_box.php on line 2

Actually file is there in my directory.I am using ubuntu (OS)
How can we prevent this warning?

How to solve:

Note: My answer below has turned out to be popular, but I didn’t really answer the question properly. It’s not about suppressing the warning, it’s about fixing the bug that caused the warning. I’ll leave it here for posterity.


The proper way to prevent the warning would be to check if the first exists first and don’t try to include it if it doesn’t.

if (file_exists($includefile)) {
  include_once($includefile);
}

(obviously replace $includefile with the file you’re including)

The quick and dirty way to do it, which I DO NOT recommend, would be to suppress the warning with the @ expression.

@include_once($includefile);

Note that when suppressing a warning this way, PHP’s error handling code still runs but with PHP’s error_reporting ini value temporarily changed to ignore it. As a rule of thumb this isn’t a good idea because it can mask other errors.

As others have pointed out, “1” is an unusual filename for a PHP file, but I’ll assume you have a specific reason for doing that.

Answer:

Obviously the issue here is that PHP can’t find the file you’re trying to include. To reduce confusion about what the current path is, I usually make it an absolute path like this:

// inc.php is in the same directory:
include (dirname(__FILE__) . "/inc.php");

// inc.php is in a subdirectory
include (dirname(__FILE__) . "/folder/inc.php");

// inc.php is in a parent directory
include (dirname(dirname(__FILE__)) . "inc.php");

It’s probably a bit over the top, but you can be sure to know where PHP is looking for your files.

Answer:

that’s quite unusual name for the php file – a single digit 1.
are you sure you have such a file?

Answer:

You’re probably trying a statement such as this:

include('header.php') or die('Include file not found.');

In this case what’s happening is operator precedence is evaluating it like this:

include ( ('header.php') or die('Include file not found.') );

And because the string 'header.php' does not evaluate to false, it’s being cast to a 1 in this context.

You can fix this by rearranging parentheses:

(include 'header.php') or die('Include file not found.');

Note that include is a keyword rather than a function call so no parentheses are required for its argument.

Leave a Reply

Your email address will not be published. Required fields are marked *