PHP - “if (!$_POST)”不应该足以(不必指定字段名称)来检测数据是否通过具有 1 个字段的表单传递


PHP - shouldn't 'if (!$_POST)' be enough (without having to specify the field name) to detect if data is being passed through a form with 1 field?

所以我安装了最新版本的Xampp,在htdocs目录中,我有一个htm页面,其中包含一个非常简单的表单,只有一个文本字段和一个提交按钮,单击该按钮时,链接到一个php页面,该页面打印一条消息,说"您键入的是:",然后是键入的内容。如果字段中实际上没有键入任何内容,则单击提交按钮后,php页面将显示一条错误消息,指出"错误:您没有键入任何内容"。

以下是 htm 页面的代码:

<html>
<head>
</head>
<body>
<center>
<form action="p1.php" method="post">
  Type something:
  <input type="text" name="nom">
  <input type="submit" value="SEND">
</form>
</center>
</body>
</html>

这是 php 页面的初始代码:

<html>
<head>
</head>
<body>
<?PHP
if (!$_POST) {echo "Error: you didn't type anything";}
else {echo "What you typed is: " . $_POST["nom"];}
?> 
</body>
</html>
因此,使用此php代码,如果我在字段中键入任何内容并单击提交按钮,php页面将显示"您键入的内容:",然后

是键入的内容,但是如果我实际上没有在该字段中键入任何内容并单击提交按钮,php页面将显示"您键入的内容:",然后什么都没有,而不是显示"错误: 你什么都没打"。

但是,我发现如果我将"if (!$_POST)"更改为"if (!$_POST["nom"])",那么如果我没有在该字段中键入任何内容,php 页面将显示"错误:您没有键入任何内容"...问题解决了。

但这让我感到惊讶,因为我在我的课程材料中看到了一个示例(它被称为自调用形式或类似的东西),其中使用了"if (!$_POST)"。在这里:

<html> 
<head> 
    <title>Me llamo a mi mismo...</title> 
</head> 
<body> 
<? 
if (!$_POST){ 
?> 
<form action="auto-llamada.php" method="post"> 
Nombre: <input type="text" name="nombre" size="30"> 
<br> 
Empresa: <input type="text" name="empresa" size="30"> 
<br> 
Telefono: <input type="text" name="telefono" size=14 value="+34 " > 
<br> 
<input type="submit" value="Enviar"> 
</form> 
<? 
}else{ 
echo "<br>Su nombre: " . $_POST["nombre"]; 
echo "<br>Su empresa: " . $_POST["empresa"]; 
echo "<br>Su Teléfono: " . $_POST["telefono"]; 
} 
?> 
</body> 
</html> 

那么为什么"如果(!$_POST)"在我的情况下不起作用呢?(使用Mozilla作为浏览器)

当像这样发布并且字段为空时,它仍然被保存为值。

var_dumping这个

<form method="post" action="fgc.php">
<input type="text" name="horse">
<input type="submit">
</form>

将返回:

array(1) { ["horse"]=> string(0) "" }

在PHP中,$_POST超全局总是被定义的,无论该方法是否实际POST,或者是否有任何数据被发布。 但是,如果它不是POST,或者没有数据,则该数组将为空。

如果将数组转换为布尔值,则如果数组中没有元素,则该值将为 false。

<?php
var_dump(isset($_POST)); // Always TRUE
var_dump(!!$_POST); // TRUE if data was posted (even if empty fields), FALSE otherwise

您的文档说使用 !$_POST 的原因是,通常页面将使用 GET 方法加载,在这种情况下,$_POST将是一个空数组。

试试这段代码

if($_SERVER['REQUEST_METHOD'] == 'POST'){ // if the form was submitted
  if(isset($_POST['name']) && !empty($_POST['name'])){ // basic validation
   // # Don't forget XSS sanitizing !
   $name = htmlspecialchars($_POST['name']);
   // Add data to DB or something
  }else{
   echo 'Error: Required field "name"';
  }
}