Wednesday, 11 September 2013

Define web root dir - consant works on include but not redirect

Define web root dir - consant works on include but not redirect

I'm trying to create a constant which defines my web root dir, which I can
use for constructing paths for requires, header redirects, images, etc.
I need the constant to work when used in files in the root folder and sub
folders. I know I could easily hard code the paths with ../ etc, but the
main reason I'm trying to get this to work (apart from clean code) is so I
can re-use the code on various sites on different servers, where the path
may vary.
my dir structure
/
index.php
/library
libSetPathRoot.php
Document Root
echo $_SERVER["DOCUMENT_ROOT"];
Returns: /home/james/web/sites/
The "sites" dir contains various document roots defined in sites-available
(so I can work on different scripts).
File contents
/index.php
require_once('library/libSetPathRoot.php'); //works fine.. of course
/library/libSetPathRoot.php
define("PATHROOT", realpath(__DIR__ .'/..').'/');
The above returns my root correctly:
echo PATHROOT;// /home/james/web/sites/site3/
I've tried the following and various other code to define a root path.
These, and others, didn't work for redirect(), include(), nothing at all:
define ('PATHROOT', getenv("DOCUMENT_ROOT"));
define ('PATHROOT', basename(dirname((__DIR__))));
echo PATHROOT;
Everything else seemed to return "site3" only.
The working define works for include() and require() regardless of where
in the dir structure it is placed. ie if in file in sub dir to root
calling root or other sub dir to root, in a file in root, included file
etc.
But I just cannot get this working for header() redirect. Again,
regardless of where I use it - root scripts, sub folder scripts, included
scripts. Maybe I need another approach, but have read numerous options and
tried them extensively (half a day spent).
Why is my define working for includes but not header redirect, and how can
I make it work on all? Or do I have to use two methods, one for include
and one for redirects?

No comments:

Post a Comment