2016-04-13 47 views
0

我的URL路径:如何避免由“+”符号引起的错误GET请求?

https://mypage/main.php?dir=farm/1234_animal_fred+sam_cats 

我请求用GET方法的数据:

$dir = $_GET['dir']; 
echo $dir; 

但我的结果是

farm/1234_animal_fred sam_cats 
+4

不要在你的URL中使用'+'但是'%2B'代替; https://mypage/main.php?dir = farm/1234_animal_fred%2Bsam_cats – Unex

+0

好的,非常感谢! – Jarla

+0

“1234_animal_fred + sam_cats”零件是如何生产的? – Mike

回答

2

即使Unex公司的答案是正确的,这种特殊情况下,我不确定他是否会丢失其他字符可能在您的数据库中可能会导致某些内容失败,或者更糟糕的是,可能会导致您遇到XSS漏洞。因此,而不是使它在这一个单一的情况下,通过做工作:

$url = str_replace('+', '%2B', $url); 

你想,而不是使之成为所有箱子工作。所以,假设你已经从你的数据库中的以下内容:

$file_path = 'farm/1234_animal_fred+sam_cats'; 

要正确地做这项工作,你需要做的urlencode() URL的一部分,但是从this answer你会发现,这是不够的,保护你免受XSS攻击。因此,你还需要在字符串中使用htmlspecialchars()

$url = 'https://mypage/main.php?dir='; 
$file_path = 'farm/1234_animal_fred+sam_cats'; 
$url .= htmlspecialchars(urlencode($file_path)); 

echo $url; // https://mypage/main.php?dir=farm%2F1234_animal_fred%2Bsam_cats 

和去这个网址时,你可以看到,PHP得到正确的值:

print_r($_GET) output: 
Array 
(
    [dir] => farm/1234_animal_fred+sam_cats 
) 
+0

非常感谢!这对我很有帮助! – Jarla

-2

你应该总是使用原料进行urlencode( $ url)来编码你的网址。

http://php.net/manual/en/function.rawurlencode.php

现金去提意见,对不起你们我是为了迅速作出反应。

+1

不!您可以不使用该功能对URL进行编码!该函数允许对字符串进行编码,以便可以在URL中使用它们。这是一个巨大的差异! – arkascha

+2

不,你应该'永不'编码的URL urlencode' :) – Eihwaz

+0

@arkascha所以这是完全不可能的使用URL内的'+'? – Jarla

1

请勿在您的网址中使用+,而应使用%2B

这是结果:

https://mypage/main.php?dir=farm/1234_animal_fred%2Bsam_cats

希望这有助于,

+1

这是我的意见 – Unex