2011-12-28 46 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