我在页脚中有一个表单,我在localhost 127.0.0.1/form.php 上运行php文件,显然如果在HTML中使用php代码它只会是评论说。根据我在PHP文档中的理解,我需要直接运行php文件。
代码基于W3Schools PHP Form Required tutorial:
<!DOCTYPE html>
<html>
<body>
<footer>
<form method="post" action="form.php">
<input type="text" name="name" placeholder="Name"><span class="form-error">*<?php echo $nameError;?></span><br>
<input type="submit" value="Send">
</form>
<?php
// define variables and set to empty values
$name = ""; // The variable is defined at the global scope
$nameError = ""; // The error variable is defined at the global scope
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($POST['name'])) {
$nameError = 'Name required'; }
else {
$name = test_input($_POST["name"]); }
}
// The function that will validate the form
function test_input($data) {
$data = trim($data); // The data is stripped of unnecesary characters
$data = stripslashes($data); // Backslashes '\' are removed
$data = htmlspecialchars($data); // Converts special characters into HTML entities
return $data
}
?>
如果我将文本留空,则不会在范围内回显错误,所以我尝试调试它
<?php
// Debugging test_input($data)
echo $name;
echo "<br>";
echo $nameError;
echo "<br>";
?>
无论我在输入中提交什么内容,$name
始终为空,而$nameError
始终是回显。
所以我认为这个函数可能没有返回任何东西,我做了一些调试
// Debugging without the function
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo $name;
echo "<br>";
}
// Debugging after each iteration of whats inside the function (without return)
$data = trim($data); // The data is stripped of unnecesary characters
echo $name;
echo "<br>";
$data = stripslashes($data); // Backslashes '\' are removed
echo $name;
echo "<br>";
$data = htmlspecialchars($data); // Converts special characters into HTML entities
echo $name;
echo "<br>";
?>
如果我介绍,例如& \ a
我的输出是:
*a blank line*
Name required
& \ a
& \ a
& \ a
& \ a
显然,内置函数的php并没有做他们应该做的事情。 stripslashes($data)
没有删除反斜杠,&
在查看&
后应显示为htmlspecialchars($data)
。
我甚至评论了test_input($data)
内的所有内容,以便它看起来像这样
function test_input($data) {
return $data }
仍然没有得到任何结果。有什么想法吗?另外,为什么函数test_input($data)
稍后在脚本中定义而不是之前定义(尝试在定义变量之前放置它仍然不起作用)。提前谢谢。
答案 0 :(得分:0)
&#34;你有一个拼写错误:空($ POST [&#39;名称&#39;])应为空($ _ POST [&#39; name&#39;])&#34; @Magnus Eriksson
&#34;因为您在尝试回显变量后定义并设置变量$ nameError。&#34; @Magnus Eriksson