doulu1945 2014-04-14 08:52
浏览 37
已采纳

PHP Url相对和绝对

I have this class:

class PageBuilder {
    public function GetHeader() {
        include(dirname(dirname(__FILE__)) . '/template/header.php');
    }
}

Which when called will insert the header file into my page. All is good.

$page_builder->GetHeader();

In the header.php is the top of the HTML file which includes a menu. My problem is, depending on where the PageBuilder gets called from changes the menu link URLs.

How do I make sure they are always relative to the root folder.

dirname(__FILE__) doesn't work because it turns the URL into file:///, also I really don't want to append the entire http://www.blahblah.com/blah because if it is relative to the root it doesn't matter about any of that.

EDIT

So as someone posted you can use $_SERVER[''] but which one is reliable, no doubt PHP will have put in some blinding caveats.

See I was thinking $_SERVER['SERVER_ADDR'] or $_SERVER['SERVER_NAME'] or $_SERVER['HTTP_HOST'] .....

Going $_SERVER['HTTP_HOST'] for now .. result is fail.

Just prefixing with / resolves to the localhost root so my links are localhost/admin/profile.php rather than localhost/TestApp/admin/profile.php, Do I have to actually specify that it sits in folder named TestApp?

  • 写回答

2条回答 默认 最新

  • dongya2029 2014-04-14 09:33
    关注

    After trial and error with the help of @deceze I simply pass my URL through a routing class which prefixes the URL with '/TestApp/' this can be change easily if the project gets moved because the use of classes.

    So I do:

    <a href="<?php $url_routing->ParseUrl('admin/account/logout.php') ?>">Log Out </a>
    

    Gets passed through:

    public function ParseUrl($url) {
        return '/TestApp/' . $url;
    }
    

    It is hardly best practice, but there can't be best practices with a language that doesn't follow any itself.

    Looking at @Anthony answer of using $_SERVER['PHP_SELF']; it does always give the TestApp folder. Needs more looking into but I will take that. I assume its relative to the server address.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于php录入完成后,批量更新数据库
  • ¥15 请教往复密封润滑问题
  • ¥15 cocos creator发布ios包
  • ¥15 comsol压电材料数据
  • ¥35 用python实现除法算法中goldschmidt算法
  • ¥15 汇编代码转换成C代码
  • ¥15 除法算法中的归一化具体是怎么变的?
  • ¥20 集成电路的逻辑电路和晶体管简化图
  • ¥15 下载windows builder后的问题
  • ¥15 端口连接数为什么会有限制