Request string without GET arguments [duplicate]

2020-02-17 06:14发布

Is there a simple way to get the requested file or directory without the GET arguments? For example, if the URL is http://example.com/directory/file.php?paramater=value I would like to return just http://example.com/directory/file.php. I was surprised that there is not a simple index in $_SERVER[]. Did I miss one?

12条回答
做个烂人
2楼-- · 2020-02-17 06:37

Not everyone will find it simple, but I believe this to be the best way to go around it:

preg_match('/^[^\?]+/', $_SERVER['REQUEST_URI'], $return);
$url = 'http' . ('on' === $_SERVER['HTTPS'] ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $return[0]


What is does is simply to go through the REQUEST_URI from the beginning of the string, then stop when it hits a "?" (which really, only should happen when you get to parameters).

Then you create the url and save it to $url:
When creating the $url... What we're doing is simply writing "http" then checking if https is being used, if it is, we also write "s", then we concatenate "://", concatenate the HTTP_HOST (the server, fx: "stackoverflow.com"), and concatenate the $return, which we found before, to that (it's an array, but we only want the first index in it... There can only ever be one index, since we're checking from the beginning of the string in the regex.).

I hope someone can use this...

PS. This has been confirmed to work while using SLIM to reroute the URL.

查看更多
放我归山
3楼-- · 2020-02-17 06:44

I actually think that's not the good way to parse it. It's not clean or it's a bit out of subject ...

  • Explode is heavy
  • Session is heavy
  • PHP_SELF doesn't handle URLRewriting

I'd do something like ...

if ($pos_get = strpos($app_uri, '?')) $app_uri = substr($app_uri, 0, $pos_get);
  • This detects whether there's an actual '?' (GET standard format)
  • If it's ok, that cuts our variable before the '?' which's reserved for getting datas

Considering $app_uri as the URI/URL of my website.

查看更多
做自己的国王
4楼-- · 2020-02-17 06:44

I had the same problem when I wanted a link back to homepage. I tried this and it worked:

<a href="<?php echo $_SESSION['PHP_SELF']; ?>?">

Note the question mark at the end. I believe that tells the machine stop thinking on behalf of the coder :)

查看更多
祖国的老花朵
5楼-- · 2020-02-17 06:45

Why so complicated? =)

$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];

this should really do it man ;)

查看更多
家丑人穷心不美
6楼-- · 2020-02-17 06:46

Solution:

echoparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

查看更多
贪生不怕死
7楼-- · 2020-02-17 06:48

I know this is an old post but I am having the same problem and I solved it this way

$current_request = preg_replace("/\?.*$/","",$_SERVER["REQUEST_URI"]);

Or equivalently

$current_request = preg_replace("/\?.*/D","",$_SERVER["REQUEST_URI"]);
查看更多
登录 后发表回答