OOP验证PHP

时间:2017-09-12 17:34:35

标签: php oop

目前我尝试通过OOP php验证电子邮件地址,以便稍后添加其他功能,但是当我插入有效的电子邮件地址时验证仍然失败,我想我的数组可能设置错误但我不完全确定,另外我尝试过不同的操作员来检查电子邮件功能是否会输出不同的结果,但是如上所述它似乎总是失败,任何建议都会受到赞赏

class Login
{   
    private 
    $email,
    $password,
    $database,
    $db = null;

    public function __construct()
    {
        $this->db = new Database;
    }

    public function validEmail($email)
    {   
        return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);  
    }   
}






      <?php 
require "classes/Login.class.php";
$validate = new Login();

        require "loadclasses.php";

            if ($_SERVER['REQUEST_METHOD'] == 'POST')
            {
                $email = $pass = "";
                $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);     

                $email = $post['email-login'];
                $pass = $post['password-login'];        
                $errors = array();


                $fields = array(
                 'email-login' => array(        
                     'validate' => 'validEmail',
                     'message'   => 'Enter a valid email address'
                    )
                );


                foreach($fields as $key => $value) 
                {
                    if(isset($fields[$key])) 
                    {
                        $errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
                    }
                }



                if(empty($errors)) 
                {
                     $success = ['response' => 'true']; 
                     session_start();
                }   

            }



        header('Content-Type: application/json');
        if (empty($errors))
        {
            echo json_encode($success);
        }
        else
        {
            echo json_encode(["errors" => $errors]);
        }           

1 个答案:

答案 0 :(得分:0)

正如评论中已经提到的那样 - 您不使用Login类中的函数。

那么,您当前代码的工作原理如何:

$fields = array(
  'email-login' => array(        
     'validate' => 'validEmail',
     'message'   => 'Enter a valid email address'
  )
);

foreach($fields as $key => $value) 
{
    // isset($fields[$key]) is ALWAYS true
    if(isset($fields[$key])) 
    {
        $errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
    }
}

你真正应该做的是:

$fields = array(
  'email-login' => array(        
     'validate' => 'validEmail',
     'message'   => 'Enter a valid email address'
  )
);
// instantiate object of Login class
$login = new Login();

foreach($fields as $key => $value) 
{
    // call a function `$value['validate']` (it is `validEmail`)
    $validation_result = $login->{$value['validate']}($email);

    // if validation fails - add error message
    if(!$validation_result) 
    {
        $errors[] = ['name' => $key, 'error' => $value['message']];
    }
}

btw $post是一个错误的变量名,我想它是$_POST