2011-12-28 40 views
1
<?php 

$current_subject = $_GET['subject_id']; 
$current_content = $_GET['note_id']; 

echo "<form method=\"post\" action=mainpage.php?subject_id=".$current_subject."&note_id=".$current_content.">"; 

?> 
    <input type='text' name='list_item' value=''> 
    <input type='submit' name="new_item" value="New Item"> 
</form> 

問題是,當GET變量之一是兩個單詞鏈接不會這樣寫。因此,舉例來說,如果$current_subject="Advanced Chemistry"$current_content="Valence Electrons"鏈接會出來爲:PHP GET方法空間錯誤

<form method=​"post" action=​"mainpage.php?subject_id=Advanced" chemistry&note_id=​"Valence" electrons>​ 
+0

+1一個清晰,簡潔的問題。 – 2011-12-28 23:48:33

回答

5

您需要urlencode()變量,像這樣:

<?php 

$current_subject = $_GET['subject_id']; 
$current_content = $_GET['note_id']; 

$subject = urlencode($current_subject); 
$content = urlencode($current_content); 

$action = "mainpage.php?subject_id=" . $subject . "&note_id=" . $content; 

?> 

<form method="post" action="<?php echo $action; ?>"> 
    <input type="text" name="list_item" value=""> 
    <input type="submit" name="new_item" value="New Item"> 
</form> 

此外,你應該確認該數據的習慣得到。你可能想檢查它們是整數。

+2

您錯過了urlencode:'echo urlencode(「mainpage.php?subject_id = 1234łóść&note_id = absd saas」)'given mainpage.php%3Fsubject_id%3D1234 +%C5%82%C3%B3%C5%9B%C4% 87%26note_id%3Dabsd + saas' – piotrekkr 2011-12-28 23:32:23

+0

感謝您指出這一點!現在修復。由於我曾在PHP工作過一段時間。 – 2011-12-28 23:34:44

4

使用urlencode()rawurlencode()

0

你應該看看PHP的urlencode()

$current_subject = urlencode($_GET['subject_id']); 
$current_content = urlencode($_GET['note_id']); 
3

始終報價您的屬性和逃避你的數據。引用,它的工作:

<?php 

$current_subject = $_GET['subject_id']; 
$current_content = $_GET['note_id']; 

echo "<form method=\"post\" action=\"mainpage.php?subject_id=" . $current_subject . "&note_id=" . $current_content . "\">"; 

?> 
    <input type="text" name="list_item" value="" /> 
    <input type="submit" name="new_item" value="New Item" /> 
</form> 

但是,當然,你應該先urlencode它:

<?php 
$current_subject = $_GET['subject_id']; 
$current_content = $_GET['note_id']; 
$url = 'mainpage.php?subject_id=' . urlencode($current_subject) . '&note_id=' . urlencode($current_content); 
?> 
<form method="POST" action="<?php echo $url; ?>"> 
    <input type="text" name="list_item" value="" /> 
    <input type="submit" name="new_item" value="New Item" /> 
</form> 
+1

看起來您忘記了第二個代碼段中{$ url}的雙引號。 – Corbin 2011-12-28 23:51:37

+0

@Corbin:非常真實!固定。 – Ryan 2011-12-29 00:18:51

1

我可能會使用http_build_query

$query = http_build_query(array('subject_id' => $_GET['subject_id'], 'foo' => 'bar')); 
<form action="mainpage.php?<?php echo $query; ?>"> 

我有一個懷疑,$query也應該是htmlentities'd。
http_build_query處理URI編碼,但我不確定它是否應該在HTML之上編碼(畢竟它是HTML屬性)。

+0

不用擔心使用'htmlentities',它逃脫的任何內容在URL中也是無效的。 – Ryan 2011-12-29 02:55:00

+0

這意味着http_build_query(或urlencode)已經逃脫了任何hmmlentities?這就是我的想法,但不確定。如果是這種情況,再次調用它的時候不會有什麼壞處。只是浪費精力:)。 – Corbin 2011-12-29 03:56:08