php 使用session_start()和jQuery进行表单验证不会显示这两个错误,我的错误在哪里?

dly7yett  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(115)

这是我的UsersController,PHP中的验证在这里,我已经在索引中启动了会话,但我不确定在哪里结束它以及如何结束:

<?php
    public function createAction(){
        require "Views/Users/new.php";      
            if (empty($_POST["email"])) {
                $validation = false;
                array_push($errors, "Field 'email' is required.");
            }elseif (!filter_var($_POST["email"],FILTER_VALIDATE_EMAIL)) 
                {
                $validation = false;
                array_push($errors, "Field'email' invalid format.");
            }
            if ($validation) {
                $user = new Users();
                $user->email = $_POST["email"];
                $status = Users::insert($user);
            }
            if ($validation) {
                $_SESSION["users-create-errors"] = $errors;
                if (array_key_exists("users-create-errors", $_SESSION)) 
                {
                    unset($_SESSION["users-create-errors"]);
                }

        }
    }
  } 

 }
yfwxisqw

yfwxisqw1#

<?php
public function createAction(){
    require "Views/Users/new.php";  

    // initialise $validation and $errors
    $validation = true;
    $errors = [];

    if (empty($_POST["email"])) {
        $validation = false;
        array_push($errors, "Field 'email' is required.");
    } elseif (!filter_var($_POST["email"],FILTER_VALIDATE_EMAIL)) {
        $validation = false;
        array_push($errors, "Field'email' invalid format.");
    }
    if ($validation) {
        $user = new Users();
        $user->email = $_POST["email"];
        $status = Users::insert($user);
    }

    // this probably should be !$validation
    if (!$validation) {

        // you set $_SESSION["users-create-errors"]
        // and then if its set which it of course will be 
        // you destroy it?????

        //$_SESSION["users-create-errors"] = $errors;
        //if (array_key_exists("users-create-errors", $_SESSION)) {
            //unset($_SESSION["users-create-errors"]);
        //}

        // just set it to a new value which will overwrite anything
        // that is left in there. But this shoudl be cleaned out
        // when the errors have been reported to the user
        $_SESSION["users-create-errors"] = $errors;

}

相关问题