Dec
3
So ... Sometimes, your need to know relative path for coding 'include()' or 'require()' in PHP but you script reside in different sub directories and different levels and it got messing.
How could you detect the Relative Path and Absolute Path on your document root ? And later use single variables or constant and specify relative path of included script relative to document root instead ...
This is the solution. But this may not work as expected if you are using URL rewrite or alias on some web server.
<?php
define(WEB_ROOTDIR, preg_replace('/\/[^\/]+/','../',dirname($SERVER['PHP_SELF']))))
require_once(WEB_ROOTDIR . '/adodb/adodb.inc.php');
require_once(WEB_ROOTDIR . '/include/myclass.php');
...
...
?>
To see how this work ... Try playing around your sub directory of your document root by put this script in various place.
<?php
header('Content-Type: text/plain');
echo $_SERVER['PHP_SELF'] . "\n";
echo dirname($_SERVER['PHP_SELF']) . "\n";
echo preg_replace('/\/[^\/]+/','../',dirname($_SERVER['PHP_SELF'])) . "\n";
echo realpath('./' . preg_replace('/\/[^\/]+/','../',dirname($_SERVER['PHP_SELF']))) . "\n";?>
?>
How could you detect the Relative Path and Absolute Path on your document root ? And later use single variables or constant and specify relative path of included script relative to document root instead ...
This is the solution. But this may not work as expected if you are using URL rewrite or alias on some web server.
<?php
define(WEB_ROOTDIR, preg_replace('/\/[^\/]+/','../',dirname($SERVER['PHP_SELF']))))
require_once(WEB_ROOTDIR . '/adodb/adodb.inc.php');
require_once(WEB_ROOTDIR . '/include/myclass.php');
...
...
?>
To see how this work ... Try playing around your sub directory of your document root by put this script in various place.
<?php
header('Content-Type: text/plain');
echo $_SERVER['PHP_SELF'] . "\n";
echo dirname($_SERVER['PHP_SELF']) . "\n";
echo preg_replace('/\/[^\/]+/','../',dirname($_SERVER['PHP_SELF'])) . "\n";
echo realpath('./' . preg_replace('/\/[^\/]+/','../',dirname($_SERVER['PHP_SELF']))) . "\n";?>
?>
Now ... What if I am using url_rewrite and above code not working ? ... You need to specify your WEB_ROOTDIR as absolute path, using __FILE_ instead, for example, this file is reside in document root.
<?php
define(WEB_ROOTDIR, realpath(dirname(_FILE_)));
...
...
?>
this file is in <docroot>/include/config.inc.php
<?php
define(WEB_ROOTDIR, realpath(dirname(_FILE_) . '/..'));
...
...
?>



0 Trackbacks