开发者

html/php: how to handle absolute url's?

Is the html <base> tag safe to use in terms of browser support? Or should I generate a root path with PHP which i then add like this <a href="<?=BASE?>somepage.html">somepage</a> which makes up a absolute url.

using the base tag like this <base href="<?=BASE?>" /> I am then able to use links like this

<a href="somepage.html">somepage</a>

now I am fully aware that it would be much easier to just do this without using the base tag:

<a href="/somepage.html">somepage</a>

but how do I test locally then with a base url of http://localhost/testsite/ ???

edit: thanks guys, your the people开发者_StackOverflow who make the stackoverflow community so great :)


My advice would be to use absolute URLs beginning with a slash, and just set up a virtual host that uses /localhost/testsite/ as its document root. Then you could leave the absolute URLs and just access your site at something like http://testsite/ locally.


You've definitely given this some thought but I would like to throw one more consideration into the mix. If you are writing a web application, you should construct it in such a way that you can install it into any sub-directory in the future and it will continue to work with little change.

This means that href's, src's, action's and even HTTP Location headers will need to be aware of such a change. That's why I recommend prepending your uri's with <?php echo SITE_BASE ?> or whatever you want to call it.

Debate can rage on as to whether SITE_BASE should contain a trailing slash.


I like the first option, outputting a base directory in PHP tags

<a href="<?=BASE?>somepage.html">somepage</a>

the very best. This makes your site independent from which directory it is installed in (you may not be able to change virtual host settings on shared hosting packages). It is also easy to outsource image files to a different server/subdomain if ever need be.

<base> is safe to use in terms of browser support, but I personally recommend strongly against using it for reasons of code maintainability. <base> changes the rules for how URLs are processed; you need to keep the base in mind for all relative URLs; and is very easy to overlook. From a programming perspective, it feels like a dirty fix.


Comming back to this question 2 years later, I now realise that the best way to handle absolute URLs is to put the URL into a wrapper function, for example like this:

<a href="<?php echo url('/somepage.html');?>">somepage</a>

the wrapper function then gives you full control over the URL handling

function url($url){
    if(strpos($url,'/')===0){
        return 'http://localhost/testsite'.$url;
    }else{
        return $url;
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜