php 处理 get 参数中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8155788/
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 04:04:04  来源:igfitidea点击:

Handling a space in a get parameter

phpget

提问by algorithmicCoder

I am using a command like

我正在使用类似的命令

 $page = file_get_contents($url);

where

在哪里

$url = "http://www.site.com/search/index.cfm?tab=names&workername=firstname lastname";

When the url is typed directly in the browser chrome adds a %20in between firstname and lastname and the website handles things properly.

当 url 直接在浏览器中输入时,chrome 会%20在名字和姓氏之间添加一个,网站会正确处理。

However when I use $url with a space, file_get_contents grabs only results that match the firstname and isn't aware that workername = "firstname lastname"

但是,当我使用带有空格的 $url 时,file_get_contents 只抓取与名字匹配的结果,并且不知道 workername = "firstname lastname"

When I explicitly add "%20" in between it returns NULL...

当我在它之间明确添加“%20”时,它返回NULL......

What's the work around?

有什么工作?

Thanks guys!

谢谢你们!

回答by animuson

A few problems:

几个问题:

  1. I hope this is just because you quick-typed it here, but you need to have the string in single quotes.
  2. There is no query string for the URL because you never start it with the ?, so no, neither of those variables will exist in $_GET.
  3. You dohave to redefine spaces as %20for URLs.
  1. 我希望这只是因为您在这里快速输入,但您需要将字符串放在单引号中。
  2. URL 没有查询字符串,因为您永远不会以 开头?,所以不,这些变量都不会存在于$_GET.
  3. 必须重新定义空间的%20针对URL。


$url = 'http://www.site.com/search/?tab=names&workername=firstname%20lastname';
       ^                           ^                              ^^^        ^


Edit:
It is possible that the website you're trying to query is ignoring them as GET variables. Have you tried adding this code to explicitly say it is a GET request?

编辑:
您尝试查询的网站可能将它们作为 GET 变量忽略。您是否尝试添加此代码以明确表示这是一个 GET 请求?

$options = array(
  'http' => array('method' => "GET", 'header' => "Accept-language: en\r\n")
);
$context = stream_context_create($options);
file_get_contents($url, false, $context);

回答by gabriel capparelli

You need to urlencodeyour text:

你需要urlencode你的文字:

$fixed= urlencode($workername);
$url = 'http://www.example.com/search/?tab=names&workername='.$fixed;