在登录表单上测试错误消息时,Foreach无效

时间:2015-02-16 19:27:28

标签: php

我又回来了。我已经为form-process.php;

制作了这个php代码
    <?php
//prevent access if they haven't submitted the form.
if (!isset($_POST['submit'])) {
die(header("Location: form.php"));
}

session_start();

$_SESSION['formAttempt'] = true;

if (isset($_SESSION['error'])){
    unset($_SESSION['error']);
}

$required = array ("name", "email", "password1", "password2");

$_SESSION['error'] = array();

//Check required fields
foreach ($required as $requiredField) {
    if(!isset($_POST[$requiredField])  || $_POST[$requiredField] == "") {
        $_SESSION['error'] [] = $requiredField . "is required." ;
    }
}

//Validating Text in name
if (!preg_match('/^[/w.]+$/',$_POST['name'])) {
    $_SESSION['error'] [] = "Name must be letters and numbers only.";
}

//Validating Drop Down Selection
$validStates = array("Alabama","California", "Colorado", "Florida", "Illinois", "New York");
if (isset($_POST['state']) && $_POST['state'] != "") {
    if(!in_array($_POST['state'], $validStates)) {
        $_SESSION['error'] []="Please choose a valid state.";
    }
}

//Validating an Email
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $_SESSION['error'] = "Invalid email address";
}

//Ensure that the Passwords Match
if ($_POST['password1'] != $_POST['password2']) {
    $_SESSION['error'] [] = "Passwords do not match.";
}

//Final Disposition
if (isset($_SESSION['error']) && count ($_SESSION['error']) > 0) {
    die(header("Location: form.php")); 
} else {
    unset($_SESSION['formAttempt']);
    die(header("Location:success.php"));
}
?>

登录表单Div错误php代码;

<?php 
       if (isset($_SESSION['error']) && isset($_SESSION['formAttempt'])) {
           unset ($_SESSION['formAttempt']);
           print "Errors encountered <br />\n";
           foreach ($_SESSION['error'] as $error) {
           print $error . "<br />\n"; } 
   } 
 ?>

但是,在实际登录表单上测试时,我收到此错误:

  

警告:在第20行的E:\ XAMPP \ htdocs \ form.php中为foreach()提供的参数无效

我对PhP很陌生,所以我可能会错过一些东西,但我无法完全理解它...抱歉

1 个答案:

答案 0 :(得分:1)

$_SESSION['error'] = "Invalid email address";

这会使它成为一个字符串而不是先前初始化的数组,从而导致foreach出错。尝试:

$_SESSION['error'][] = "Invalid email address";

$_SESSION['error'] [] = "Passwords do not match.";

$ _SESSION [&#39;错误&#39;]和[]之间不应该有空格,不确定这是否会导致问题,验证中有多个地方有额外的空间。< / p>