PHP GET方法空间错误


<?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"链接将显示为:

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

您需要像这样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>

另外,您应该养成验证该数据的习惯。您可能想要检查它们是否为整数

使用urlencode()rawurlencode()

始终引用属性并转义数据。引号,它将工作:

<?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>

我可能会使用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属性)。

你应该看看php的urlencode()

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

最新更新