php 没有 GET 参数的请求字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9504608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:58:31  来源:igfitidea点击:

Request string without GET arguments

phphttpurlquery-string

提问by Nathan

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=valueI 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?

有没有一种简单的方法可以在没有 GET 参数的情况下获取请求的文件或目录?例如,如果 URL 是http://example.com/directory/file.php?paramater=value我只想返回http://example.com/directory/file.php. 我很惊讶$_SERVER[]. 我错过了一个吗?

回答by Tony Chiboucas

Edit: @T.Toduaprovided a newer answer to this questionusing parse_url.

编辑:@T.Todua使用 parse_url为这个问题提供了一个更新的答案

(please upvote that answer so it can be more visible).

(请对该答案投赞成票,以便它可以更明显)。

Edit2: Someone has been spamming and editing about extracting scheme, so I've added that at the bottom.

Edit2:有人一直在发送垃圾邮件和编辑有关提取方案的内容,所以我在底部添加了它。

parse_urlsolution

parse_url解决方案

The simplest solution would be:

echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

最简单的解决方案是:

echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

Parse_url is a built-in php function, who's sole purpose is to extract specific components from a url, including the PATH(everything before the first ?). As such, it is my new "best" solution to this problem.

Parse_url 是一个内置的 php 函数,其唯一目的是从 url 中提取特定组件,包括PATH(第一个之前的所有内容?)。因此,这是我对这个问题的新“最佳”解决方案。

strtoksolution

strtok的解决方案

Stackoverflow: How to remove the querystring and get only the url?

Stackoverflow:如何删除查询字符串并仅获取 url?

You can use strtokto get string before first occurence of ?

$url=strtok($_SERVER["REQUEST_URI"],'?');

您可以使用strtok在第一次出现之前获取字符串?

$url=strtok($_SERVER["REQUEST_URI"],'?');

Performance Note:This problem can also be solved using explode.

性能说明:这个问题也可以用explode来解决。

  • Explode tends to perform better for cases splitting the sring only on a single delimiter.
  • Strtok tends to perform better for cases utilizing multiple delimiters.
  • 对于仅在单个分隔符上拆分 sring 的情况,Explode 往往表现更好。
  • 对于使用多个分隔符的情况,Strtok 往往表现更好。

This application of strtok to return everything in a string before the first instance of a character will perform better than anyother method in PHP, though WILL leave the querystring in memory.

这个应用 strtok 在字符的第一个实例之前返回字符串中的所有内容将比PHP 中的任何其他方法执行得更好,尽管会将查询字符串留在内存中。

An aside about Scheme (http/https) and $_SERVERvars

关于 Scheme (http/https) 和$_SERVERvars的旁白

While OP did not ask about it, I suppose it is worth mentioning: parse_urlshouldbe used to extract any specific component from the url, please see the documentation for that function:

虽然 OP 没有询问它,但我想值得一提的是: parse_url应该用于从 url 中提取任何特定组件,请参阅该函数的文档:

parse_url($actual_link, PHP_URL_SCHEME); 

Of note here, is that getting the full URL from a request is not a trivial task, and has many security implications. $_SERVERvariables are your friend here, but they're a fickle friend, as apache/nginx configs, php environments, and even clients, can omit or alter these variables. All of this is well out of scope for this question, but it has been thoroughly discussed:

这里需要注意的是,从请求中获取完整 URL 不是一项简单的任务,并且具有许多安全隐患。$_SERVER变量在这里是您的朋友,但它们是善变的朋友,因为 apache/nginx 配置、php 环境,甚至客户端,都可以省略或更改这些变量。所有这些都超出了这个问题的范围,但已经进行了彻底的讨论:

https://stackoverflow.com/a/6768831/1589379

https://stackoverflow.com/a/6768831/1589379

It is important to note that these $_SERVERvariables are populated at runtime, by whichever engine is doing the execution (/var/run/php/or /etc/php/[version]/fpm/). These variables are passed from the OS, to the webserver (apache/nginx) to the php engine, and are modified and amended at each step. The only such variables that can be relied on are REQUEST_URI(because it's required by php), and those listed in RFC 3875(see: PHP: $_SERVER) because they are required of webservers.

重要的是要注意这些$_SERVER变量是在运行时填充的,无论是由哪个引擎执行(/var/run/php//etc/php/[version]/fpm/)。这些变量从操作系统传递到网络服务器(apache/nginx)到 php 引擎,并在每一步都被修改和修正。唯一可以依赖的变量是REQUEST_URI(因为 php 需要)和RFC 3875 中列出的变量(请参阅:PHP: $_SERVER),因为它们是网络服务器所必需的。

please note: spaming links to your answers across other questions is not in good taste.

请注意:在其他问题中发送指向您的答案的垃圾链接是不合时宜的。

回答by Brad

You can use $_SERVER['REQUEST_URI']to get requested path. Then, you'll need to remove the parameters...

您可以使用$_SERVER['REQUEST_URI']来获取请求的路径。然后,您需要删除参数...

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);

Then, add in the hostname and protocol.

然后,添加主机名和协议。

echo 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];

You'll have to detect protocol as well, if you mix http:and https://. That I leave as an exercise for you.$_SERVER['REQUEST_SCHEME']returns the protocol.

如果混合http:和,您还必须检测协议https://我留给你的练习。$_SERVER['REQUEST_SCHEME']返回协议。



Putting it all together:

echo $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] 
     . explode('?', $_SERVER['REQUEST_URI'], 2)[0];

...returns, for example:

http://example.com/directory/file.php

把它们放在一起:

echo $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] 
     . explode('?', $_SERVER['REQUEST_URI'], 2)[0];

...返回,例如:

http://example.com/directory/file.php



php.com Documentation:

php.com 文档:

  • $_SERVER— Server and execution environment information
  • explode— Split a string by a string
  • parse_url— Parse a URL and return its components (possibly a better solution)
  • $_SERVER— 服务器和执行环境信息
  • explode— 按字符串拆分字符串
  • parse_url— 解析 URL 并返回其组件(可能是更好的解决方案)

回答by T.Todua

Solution:

解决方案:

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

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

回答by Laurent

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
  • 爆炸很重
  • 会话很重
  • PHP_SELF 不处理 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
  • 这会检测是否存在实际的“?” (GET标准格式)
  • 如果没问题,那会在 '?' 之前削减我们的变量。保留用于获取数据

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

将 $app_uri 视为我网站的 URI/URL。

回答by Ravean

Here is a solution that takes into account different ports and https:

这是一个考虑到不同端口和 https 的解决方案:

$pageURL = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';

if ($_SERVER['SERVER_PORT'] != '80')
  $pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF'];
else 
  $pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];  

Or a more basic solution that does not take other ports into account:

或者不考虑其他端口的更基本的解决方案:

$pageURL = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']; 

回答by mahfuz

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$request_uri = $uri_parts[0];
echo $request_uri;

回答by ashleedawg

It's shocking how many of these upvoted/accepted answers are incomplete, so they don't answer the OP's question, after 7 years!

令人震惊的是,这些被赞成/接受的答案中有多少是不完整的,所以他们在 7 年后没有回答 OP 的问题!

  • If you are on a page with URL like: http://example.com/directory/file.php?paramater=value

  • ...and you would like to return just: http://example.com/directory/file.php

  • then use:

    echo $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];

  • 如果你在一个 URL 像这样的页面上: http://example.com/directory/file.php?paramater=value

  • ...而您只想返回: http://example.com/directory/file.php

  • 然后使用:

    echo $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];

回答by RasmusLD

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).


所做的只是从字符串的开头遍历 REQUEST_URI,然后在遇到“?”时停止。(实际上,只有在获得参数时才会发生)。

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.).

然后你创建 url 并将其保存到 $url:
创建 $url 时...我们所做的只是写“http”然后检查是否正在使用 https,如果是,我们也写“s”,然后我们连接“://”,连接 HTTP_HOST(服务器,fx:“stackoverflow.com”),并将我们之前找到的 $return 连接到它(它是一个数组,但我们只想要第一个索引其中...只能有一个索引,因为我们从正则表达式中的字符串开头进行检查。)。

I hope someone can use this...

我希望有人可以使用这个...

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

附注。这已被确认在使用 SLIM 重新路由 URL 时有效。

回答by RasmusLD

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"]);

回答by JKirchartz

You can use $_GETfor url params, or $_POSTfor post params, but the $_REQUESTcontains the parameters from $_GET$_POSTand $_COOKIE, if you want to hide the URI parameter from the user you can convert it to a session variable like so:

您可以使用$_GETurl 参数,或$_POSTpost 参数,但$_REQUEST包含来自$_GET$_POSTand的参数$_COOKIE,如果您想对用户隐藏 URI 参数,您可以将其转换为会话变量,如下所示:

<?php

session_start();
if (isset($_REQUEST['param']) && !isset($_SESSION['param'])) {

    // Store all parameters received
    $_SESSION['param'] = $_REQUEST['param'];

    // Redirect without URI parameters
    header('Location: /file.php');
    exit;
}
?>
<html>
<body>
<?php
  echo $_SESSION['param'];
?>
</body>
</html>

EDIT

编辑

use $_SERVER['PHP_SELF']to get the current file name or $_SERVER['REQUEST_URI']to get the requested URI

用于$_SERVER['PHP_SELF']获取当前文件名或$_SERVER['REQUEST_URI']获取请求的 URI