我的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
我的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
即使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
)
非常感謝!這對我很有幫助! – Jarla
你應該總是使用原料進行urlencode( $ url)來編碼你的網址。
http://php.net/manual/en/function.rawurlencode.php
現金去提意見,對不起你們我是爲了迅速作出反應。
請勿在您的網址中使用+
,而應使用%2B
。
這是結果:
https://mypage/main.php?dir=farm/1234_animal_fred%2Bsam_cats
希望這有助於,
這是我的意見 – Unex
不要在你的URL中使用'+'但是'%2B'代替; https://mypage/main.php?dir = farm/1234_animal_fred%2Bsam_cats – Unex
好的,非常感謝! – Jarla
「1234_animal_fred + sam_cats」零件是如何生產的? – Mike