2011-10-12 14 views
0

我有一個需要清理一下的鏈接。php,如何在REQUEST_URI上使用strip_tags或urldecode?

http://'.$_SERVER["SERVER_NAME"]."".$_SERVER["REQUEST_URI"].'" /> 

這個鏈接會產生這樣的事情:

http://www.site.com/friends.php 

其中friends.php$_SERVER["REQUEST_URI"]

有時我通過一個ID,然後鏈接:

http://www.site.com/friends.php?id=123456 

我想是使用用strip_tags或urldecode清洗這個環節,確保無論是在id傳遞是一個int,不包含字母,但我需要做的是原來的鏈接:http://'.$_SERVER["SERVER_NAME"]."".$_SERVER["REQUEST_URI"].'" />

編輯:

我希望鏈接被清理出來,所以我不能做到這一點吧:

http://www.site.com/friends.php?id=<script>alert(TK00000006)</script> 
+0

的[什麼是避免在PHP網站XSS攻擊的最佳實踐(HTTP可能重複:/ /stackoverflow.com/questions/71328/what-are-the-best-practices-for-avoiding-xss-attacks-in-a-php-site) – hakre

+0

這個例子當然暗示他們想避免XSS攻擊,但是問題點亮了與XSS有關。 –

回答

1

這是假設你只有ID在你的查詢字符串:

echo 'http://'.$_SERVER['SERVER_NAME'] 
    . $_SERVER['SCRIPT_NAME'] 
    .'?id=' 
    .filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT); 

得到的ID從id=<script>alert(TK00000006)</script>?id=00000006


備選答案:

echo 'http://'.$_SERVER['SERVER_NAME'] 
    . $_SERVER['SCRIPT_NAME'] 
    .'?id=' 
    .urlencode($_GET['id']); 

//or effectively the same thing using only $_SERVER variables, 
//but is much more robust as it handles multiple query parameters: 
echo 'http://'.$_SERVER['SERVER_NAME'] 
    . $_SERVER['SCRIPT_NAME'] 
    .$_SERVER['QUERY_STRING']; 

id=<script>alert(TK00000006)</script>得到的ID是?id=%3Cscript%3Ealert%28TK%29%3C%2Fscript%3E

+0

謝謝,你是最好的 – Patrioticcow

+0

這就是我最後想到的:'http://'.$_SERVER [「SERVER_NAME」]。$ _ SERVER ['SCRIPT_NAME']。'?id ='。urlencode(preg_replace(「/ [^ 0 -9] /「,」「,$ _ GET ['id']))' – Patrioticcow

+0

@Patrioticcow。 。 。做preg_replace和urlencode有什麼意義?我的猜測是,它給了你和我一樣的答案,但這很難看。 –

0

如果ID不能爲零,我不喜歡這樣寫道:

$id = (int)$_GET['id']; 
if ($id) 
...  // valid number > 0 
else 
...  // invalid 
+0

因爲它可能是a-z,所以我會認爲它也可以是0。 – hakre

+0

nope,你不明白我的問題。我想做鏈接本身的清理 – Patrioticcow

+0

,否則我可以做'$ id = preg_replace('/ [^ 0-9] /','',$ _REQUEST ['id']);' – Patrioticcow