tags:

views:

23

answers:

4

Hi
I have a php file at, say, localhost/foo/foo/bar.php
which includes a file at localhost/foo/included.php
I need to be able to get "localhost/foo/" as a string inside included.php
If, instead of localhost/foo/foo/bar.php, it's localhost/big/burpy/lolz/here.php (still including included.php) I still need to get "localhost/foo/"
So, I need the path of the included file and not the one that the client requested.

I know when I see the solution I'm going to feel like a doofus, but it just escapes me at the moment. Help please? thanks :)

+1  A: 

Inside your included file:

$yourdir = dirname(__FILE__);

or if you're using PHP 5.3.x:

$yourdir = __DIR__;

Get the document root from

// contains the document root, e.g. C:\xampp\htdocs
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
// strip drive letter if found
if(strpos($docRoot, ':') === 1) $docRoot = substr($docRoot, 2);

// directory of included file, e.g. C:\xampp\htdocs\include
$dirInclude = realpath(dirname(__FILE__));
// strip drive letter if found
if(strpos($dirInclude, ':') === 1) $dirInclude = substr($dirInclude, 2);

// find the document root
$rootPos = strpos($dirInclude, $docRoot);
// if the path really starts with the document root
if($rootPos === 0){
    // example: \xampp\htdocs\include
    $visibleDir = substr($rootPos, $);
    // convert backslashes to slashes and strip drive letter
    $webPath = str_replace('\\', '/', $visibleDir);
    // yields: http://localhost/include
    echo 'http://localhost' . $webPath;
}
else{
   // included file was outside the webroot, nothing to do...
}
Lekensteyn
I'd tried that, but it gives "C:\xampp\htdocs\foo\", when what I want is the URL, as the client sees it, ie, "localhost/foo/"
Matt
Since the included file can be outside the webroot, the included file does not always have a path that the client can use to request your file. But you can always play with `$_SERVER['DOCUMENT_ROOT']`, `__FILE__` and resolve it with `realpath()`.
Lekensteyn
A: 
<?php
    $level = 2;
    $path = dirname($_SERVER["PHP_SELF"]);
    while( substr_count($path,"/") > $level ){
        $path = dirname($path);
    }
    echo $path;
?>
Salman A
+1  A: 

The steps for this are:

  1. Use dirname(__FILE__) to get the folder of the include file.

  2. Get the server root using $_SERVER['DOCUMENT_ROOT']

  3. Remove the document root from the include folder to get the relative include folder

  4. Obtain the server url

  5. Append the relative include folder to the server url

kalengi
thank you! I'll try this and get back to you
Matt
A: 

I figured it out myself:

$realpath=str_replace('\\', '/', dirname(__FILE__));
$whatIwanted=substr_replace(str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath), "", -6));

There we go :) thanks for the help guys

Matt