Php include_once and absolute paths

1k views Asked by At

I'm trying to write a PHP app and right now I'm having trouble with the include_once() method. I have a folder structure like this:

/home/header.php  
/home/index.php  
/home/admin/admin.php

I have no problem accessing header.php from index.php using include_once('/home/header.php'); it works perfectly, but if I try to call include_once() in admin.php with the same parameters, it crashes.

I want to use absolute paths just so I don't have to worry about where I call the function and all that. Am I doing something wrong with absolute paths? If so, what's the correct way to do it?

1

There are 1 answers

5
daxeh On

Perhaps its advisable to use PHP magic function File which provides full path as a good practice for various reasons.

__File__

The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.

Ex:

require_once (dirname(__FILE__) . '/include.inc.php');

The following explains the differences for;

  • Include The include() statement includes and evaluates the specified file.

  • Include Once The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

  • Require require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page.

  • Require Once The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.

reference

Hope this helps.