Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Warning when using include_once()

Tags:

php

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?

like image 852
Aadi Avatar asked Apr 20 '10 04:04

Aadi


3 Answers

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.

like image 52
thomasrutter Avatar answered Nov 06 '22 13:11

thomasrutter


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.

like image 42
nickf Avatar answered Nov 06 '22 13:11

nickf


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

like image 26
Your Common Sense Avatar answered Nov 06 '22 15:11

Your Common Sense