Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of require_once dirname(__FILE__) ...?

I am using a php library which has this code: require_once dirname(__FILE__) . '/config.php';

From what I've read, dirname(__FILE__) points to the current directory.

So wouldn't it be easier to just write require_once 'config.php';?

My only guess here is that including the dirname(__FILE__) ensures that the require_once function uses an absolute rather than relative path.

like image 815
Leo Galleguillos Avatar asked Jan 15 '14 21:01

Leo Galleguillos


People also ask

What is dirname (__ file __)?

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap. php resides. (Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__) .)

What is the use of require_once in PHP?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.

What is the difference between include_once () and require_once ()?

The only difference between the two is that require and its sister require_once throw a fatal error if the file is not found, whereas include and include_once only show a warning and continue to load the rest of the page.

What is the main difference between require () and require_once ()?

The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.


1 Answers

Yes, you are right - dirname(__FILE__) ensures that the require_once function uses an absolute rather than relative path.

The __FILE__ constant represents the running script. It will return the full path and file name of the running script.

For example, if a script called database.init.php which is included from anywhere on the filesystem wants to include the script database.class.php, which lays in the same directory, you can use:

require_once dirname(__FILE__) . '/database.class.php'; 
like image 118
mate64 Avatar answered Sep 20 '22 14:09

mate64