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";?>
?>

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_) . '/..'));
...
...
?>

Posted by SF-Alpha

0 Trackbacks

  1. No Trackbacks

0 Comments

Display comments as(Linear | Threaded)
  1. No comments

Add Comment


Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA