Reputation: 22034
I'm doing a little home computing project in PHP and am creating references like this...
<a href=\"list_beer.php?order_by=name\">Beer</a>
This seems to pick up the right file. When I do includes, I seem to need a pathname.
include_once ("/var/www/common.php");
I'm sure this can't be right. Perhaps you could tell me what is the best practice for these things so that I can create scripts that aren't tied to a particular pathname (or operating system, come to that) and so that the file selected in the first example is known/can be controlled? Perhaps some settings in php.ini or apache?
Thank you.
Upvotes: 3
Views: 591
Reputation: 6896
The php ini file setting
include_path = var/www/includes
Means that you just forget all that crap about relative and absolute paths.
It matters not a wit where you call include/require.
Even in say:
/var/www/html/example.com/very/long/way/down/index.php
can contain the line;
include 'settings.php' ;
and if settings.php is in /var/www/includes/ then it will be included.
You can override the ini setting in a various places in apache too, even in .htaccess
This of course ties your application to your server settings, which some find unacceptable, but if you are not distributing your stuff, then read up on ini_get and ini_set too.
You can then go on and create natural directories in your include folder, such as /database and keep database settings in there too.
Upvotes: 2
Reputation: 157828
Actually, you need an absolute path for both.
for the web resources it should start from the web root - /
for the files you need a point where virtual path meets a filesystem one.
$_SERVER['DOCUMENT_ROOT']
is for that purpose.
so
<a href="/list_beer.php?order_by=name">Beer</a>
and
include_once ($_SERVER['DOCUMENT_ROOT']."/common.php");
will work as desired
Upvotes: 2
Reputation: 101906
You may use relative paths in PHP, too:
include_once './common.php';
This path now is relative to the script, which was intitially called.
If you leave out the dot
include_once 'common.php';
PHP will check all the paths in you include_path
and if it doesn't find a file called common.php
there, it will try to include common.php
relative to the current file.
Many people have the practice of definining a constant like ROOT
in the index.php which is used everywere else:
const ROOT = __DIR__; // as of PHP 5.3
define('ROOT', dirname(__FILE__)); // if you don't have PHP 5.3
Upvotes: 3
Reputation: 97805
You can:
$_SERVER['DOCUMENT_ROOT']
.Upvotes: 2