带有 URL 空格的 file_get_contents

8

我遇到了一个问题,即使我将空格替换为%20并且获得了这个内容,但最终浏览器获取的url会将“%20”转换为“%2520”。

以下是我的代码,请问有什么建议可以解决这个问题吗?它看起来很简单,但我卡住了:/

<?php
//$_GET['song'] will contain a song name with spaces
$song = str_replace(array("%20", "&", "?" , "/"), array(" ", "", "", ""), $_GET['song']);

// I use this to check how the GET 'song' looks after the str_replace
$list = "http://www.lyrdb.com/lookup.php?q=" . $song . "&for=fullt";
echo "list url is " . $list . "<hr>";

$content = file_get_contents("http://www.lyrdb.com/lookup.php?q=" . str_replace(" ", "%20", $song) . "&for=fullt");

echo $content;
?>

如果您前往http://webservices.lyrdb.com/lookup.php?q=red%20hot%20chili%20peppers&for=fullt,结果将输出歌词代码列表。
当我访问我的网站/?song=red hot chili peppers时,它也会将空格转换为%20,但似乎浏览器将%的转换为%25。
有人能帮我解决吗?
2个回答

19

在HTTP查询字符串中,对于单个参数始终使用urlencode(),对于多个参数使用http_build_query()

$song = $_GET['song']);
$url = "http://www.lyrdb.com/lookup.php?for=fullt&q=";
$content = file_get_contents($url . urlencode($song));

或者

$url = "http://www.lyrdb.com/lookup.php";
$query = ['for' => 'fullt', 'q' => $song];
$content = file_get_contents($url . '?' . http_build_query($query));

谢谢你,Cheery!!!(第一行后面有一个括号),但除此之外,谢谢!当我尝试同时使用urlencode和htmlentities时,会出现问题。我无法感谢你的帮助!! - d-_-b
1
@LearningDaily 当您想要使用从用户接收到的数据将某些内容输出到页面时,应该使用htmlentities和类似的函数。这有助于防止XSS攻击。urlencode用于将URL的查询参数转换为通过GET方法传输数据的RFC标准。 - Cheery
@Cheery,你看到了,htmlentities在这里有点令人困惑,所以我冒昧地将其删除,并添加了解释和另一种选择。希望你不介意。 - undefined

0
$data = json_encode($_POST);

$url = "http://www.index.com?data=";

echo file_get_contents($url . urlencode($data));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接