为什么我的PHP函数阻止其他代码正常工作?

时间:2019-10-21 22:47:25

标签: php

我的网站遇到的问题是,每当我调用函数 NoErrors(); 时,该函数之前的所有验证都会停止工作,不仅如此,而且似乎并没有在其中添加数据会议。我为用户输入提供了各种php验证。以及在PHP文档开始处初始化的变量。这包括计数器变量 $ totalErrors 以及可能需要进入会话的任何 $ _ POST 数据。

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["cust"]["email"])) {
        $emailErr = "Email is required";
        $totalErrors++;
      } else {
        $email = test_input($_POST["cust"]["email"]);
        // Check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Invalid email format";
          $totalErrors++;
        }
      }
    }

此验证用于清除用户输入。下面的功能是检查 $ totalErrors 变量是否已增加。根据变量是否增加,它将把用户重定向到“接收”页面或当前页面,以便用户纠正错误。另外,如果通过了检查,则应该将发布的数据添加到 $ _ SESSION 中。这里的大多数数据仅用于测试目的。

function NoErrors($totalErrors, $cleanName, $cleanMobile, $cleanEmail, $cleanCard, $cleanExpiry, $cleanCVV) {
 if ($_SERVER["REQUEST_METHOD"] == "POST" and $totalErrors == 0) {
  $_SESSION['cust']['name'] = $cleanName;
  $_SESSION['cust']['mobile'] = $cleanMobile;
  $_SESSION['cust']['email'] = $cleanEmail;
  $_SESSION['cust']['card'] = $cleanCard;
  $_SESSION['cust']['expiry'] = $cleanExpiry;
  $_SESSION['cust']['cvv'] = $cleanCVV;

header("Location: receipt.php");
} 
elseif ($_SERVER["REQUEST_METHOD"] == "POST" and $totalErrors > 0) {
header("Location: index.php");
}
}

NoErrors($totalErrors, $cleanName, $cleanMobile, $cleanEmail, $cleanCard, $cleanExpiry, $cleanCVV);

1 个答案:

答案 0 :(得分:0)

您的函数NoErrors()使用许多未定义的变量-$totalErrors$cleanName$cleanMobile等。如果打开错误报告,则应该看到一个这种错误。

要解决此问题,必须将所有用作参数的变量传递给函数。

function NoErrors($totalErrors, $cleanName, $cleanMobile, $cleanEmail, $cleanCard, $cleanExpiry, $cleanCVV) {
    if ($_SERVER["REQUEST_METHOD"] == "POST" and $totalErrors == 0) {
        $_SESSION['cust']['name'] = $cleanName;
        $_SESSION['cust']['mobile'] = $cleanMobile;
        $_SESSION['cust']['email'] = $cleanEmail;
        $_SESSION['cust']['card'] = $cleanCard;
        $_SESSION['cust']['expiry'] = $cleanExpiry;
        $_SESSION['cust']['cvv'] = $cleanCVV;

        header("Location: index.php");
    } 
    elseif ($_SERVER["REQUEST_METHOD"] == "POST" and $totalErrors > 0) {
        header("Location: index.php");
    }
}

NoErrors($totalErrors, $cleanName, $cleanMobile, $cleanEmail, $cleanCard, $cleanExpiry, $cleanCVV);