开发者

whats a good way of always having the correct doc root string?

if i have a menu such as

<a href="index.php">home</a>
<a href="aboutus.php">about us</a>
<a href="contact.php">contact us</a>

inside a file called menu.php

and this menu.php file gets include into pages all across the application. but what if i create a new folder and call it portfolio and in this folder there is a file named example1.php and the menu.php gets included in this file. the home,about us, and contact us links wont work anymore since their pointing to the root. so i created this function

function getRoot() {

    $self = $_SERVER['PHP_SELF'];
    $protocol = $_SERVER['https'] == 'on' ? 'https:/' : 'http:/';
    $docroot_before = explode("/", $self);
    array_pop($docroot_before);
    $docroot_after = implode("/", $docroot_before);
    $host = $_SERVER['HTTP_HOST'];

    return  $protocol.$host.$docroot_after."/";
}

and the menu now looks like this

<a href="<?=getRoot();?>index.php">home</a>
<a href="<?=getRoot();?>aboutus.php">about us</a>
<a href="<?=getRoot();?>contact.php">contact us</a>

the link should come out as  http://localhost/domain/aboutus.php (for example)
but it comes out as http://localhost:/domain/portfolio/aboutus.php (a开发者_如何转开发nd this is wrong).

what is the best way to always get the correct doc root no matter where the menu.php gets include.?


If a URL starts with a single slash (/) then it will link to the root folder. As long as your page is in the root folder (that is, http://www.example.com and not http://www.example.com/foo) then the following will work:

<a href="/index.php">home</a>
<a href="/aboutus.php">about us</a>
<a href="/contact.php">contact us</a>

If you are in a subdomain, then change the / to /subdomain/


I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it.

define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/');

$tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));
$tempPath2 = explode('/', substr(ABSPATH, 0, -1));
$tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));

for ($i = count($tempPath2); $i < count($tempPath1); $i++)
    array_pop ($tempPath3);

$urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);

if ($urladdr{strlen($urladdr) - 1}== '/')
    define('URLADDR', 'http://' . $urladdr);
else
    define('URLADDR', 'http://' . $urladdr . '/');

unset($tempPath1, $tempPath2, $tempPath3, $urladdr);

The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod_rewrite situations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜