无法使用 php & Apache2 验证 HTML 表单

Can not validate an HTML form with php & Apache2

我在页脚中有一个表格,我正在 运行 在本地主机 127.0.0.1/form.php[=45= 上创建 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).

后应该看起来像 &amp;

我什至在test_input($data)里面评论了所有内容,所以它看起来像这样

function test_input($data) {
  return $data }

而且还是一无所获。任何想法为什么?另外,为什么函数 test_input($data) 在脚本的后面定义而不是之前定义(试图在定义我的变量之前放置它但仍然不起作用)。提前致谢。

"You have a typo: empty($POST['name']) should be empty($_POST['name'])" @Magnus Eriksson

"Because you define and set the variable $nameError after you're trying to echo it." @Magnus Eriksson