How to get the same $_SERVER['REQUEST_URI'] on both localhost and live server

本小妞迷上赌 提交于 2019-12-07 10:18:54

问题


So this is the thing, Im building dispatcher class that needs to dispatch http requesd based on Request URI, so Im interesed only in part of URI that comes behind domain.

Now when im working on live server on URI like this:

www.domain.com/controller/method/params/

REQUEST_URI would return:

/controller/method/params/

But when im working on local machine i have URI like this:

localhost/project/controller/method/params/

and REQUEST_URI would return:

/project/controller/method/params/

So is there an elegant and neat way to tell php to get me only the params I need fromu URI? It dosent have to be $_SERVER['REQUEST_URI'], but I need that string the same on both live and local server?

Thanks!

Dispatcher compares current request URI with URI defined in config file. And on live server it matches, but on local machine there is one segment more then on live server.

How could I deal with this?


回答1:


Usually I configure my local webserver to respond on "test.mysite.com" and in hosts file i set test.mysite.com to 127.0.0.1, in that way i better simulate production environments, and i'm not forced to use subpaths in urls

If you use apache webserver, you can simply setup N virtual hosts.




回答2:


You can simply remove the path from the start of the URL if it exists.

$path = '/project/'; // for localhost/project/controller/method/params/
//$path = '/';       // for domain.tld/controller/method/params/

$url = getenv('REQUEST_URI');
if(strpos($url, $path) === 0)
{
    $url = str_replace($path, '', $url, 1);
}
print $url;

I haven't tested the above code so stray "/" might mess it up. You can always trim the URL with something like $url = trim($url, '/') if needed.




回答3:


$url = $_SERVER['REMOTE_ADDR'].$_SERVER['REQUEST_URI'];

is that what you want?




回答4:


I use the built in array_shift() function if localhost is detected.

if ($_SERVER['HTTP_HOST'] == 'localhost') {
    $array_uri = explode('/', $_SERVER['REQUEST_URI']);
    array_shift($array_uri);
    $uri = $array_uri;
} else {
    $uri = explode('/', $_SERVER['REQUEST_URI']);
}


来源:https://stackoverflow.com/questions/10109907/how-to-get-the-same-serverrequest-uri-on-both-localhost-and-live-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!