$_POST 检查变量和文件


$_POST checking variables and files

我有以下几行:

if ( (empty($_FILES["userFile1"]) ) or ( empty($_FILES["userFile2"]) ) or ( empty($_FILES["userFile2"]) ) ) {
    header("Location: " . "/");
}
// required fields
$required = array("userName", "userAddress", "userEmail");
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach ($required as $field) {
  if (empty($_POST["$field"])) {
    $error = true;
  }
}
// if error occurs
if ($error === true) {
    header("Location: " . "/");
}

但即使用户没有上传所有三个文件,或者即使用户将字段留空,脚本仍然会继续(我可以通过脚本后面的副作用来判断)。由于这些唯一要做的就是重定向用户,因此显然检查都不会通过。

但是,如果字段为空或文件未上传,为什么检查不起作用?

也许退出?

header("Location: " . "/");
exit;

HTTP 重定向被发送到浏览器,但 PHP 脚本继续执行。 重定向后,您始终需要退出。

试试这个

if ( (!isset($_FILES["userFile1"]) ) or ( !isset($_FILES["userFile2"]) ) or ( !isset($_FILES["userFile2"]) ) ) {
    header("Location: " . "/");
    exit;
}
// required fields
$required = array("userName", "userAddress", "userEmail");
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach ($required as $field) {
  if (!isset($_POST["$field"])) {
    $error = true;
    break;
  }
}
// if error occurs
if ($error === true) {
    header("Location: " . "/");
    exit;
}