php 注册时输入信息验证器的实现详解(2)


$username = null;
$password = null;
$repeat_password = null;
$email = null;
$msg = "";
if (isset($_POST['username']) && isset($_POST['password'])
        && isset($_POST['repeat_password']) && isset($_POST['email'])) {
    $username = addslashes(trim(stripslashes($_POST ['username'])));
    $password = addslashes(trim(stripslashes($_POST ['password'])));
    $repeat_password = addslashes(trim(stripslashes($_POST ['repeat_password'])));
    $email = addslashes(trim(stripslashes($_POST ['email'])));
    // validate
    $errors = RegisterValidator::validate($username, $password, $repeat_password, $email);
    // validate
    if (empty($errors)) {
        // save
        $dao = new UserDao();
        $user = new User();
        $user->setEmail($email);
        $last_login_ip = Utils::getIpAddress();
        $user->setLastLoginIp($last_login_ip);
        $user->setUsername($username);
        $salt = substr(sha1(mt_rand()), 0, 22);
        $hash_password = sha1($salt . $password);
        $user->setPassword($hash_password);
        $user->setSalt($salt);
        $user = $dao->save($user);
        if ($user) {
            UserLogin::setUserInfo($user);
            Flash::addFlash('注册成功!');
        }
        else {
            Flash::addFlash('对不起,由于服务器内部错误,导致注册失败。请稍后再试。');
        }
        Utils::redirect('welcome');
    }

    foreach ($errors as $e) {
        $msg .= $e->getMessage()."<br>";
    }


3.代码中Error类用于记录验证时的错误信息

复制代码 代码如下:


<?php
/**
 * Validation error.
 */
final class Error {
    private $source;
    private $message;
    /**
     * Create new error.
     * @param mixed $source source of the error
     * @param string $message error message
     */
    function __construct($source, $message) {
        $this->source = $source;
        $this->message = $message;
    }
    /**
     * Get source of the error.
     * @return mixed source of the error
     */
    public function getSource() {
        return $this->source;
    }
    /**
     * Get error message.
     * @return string error message
     */
    public function getMessage() {
        return $this->message;
    }
}
?>

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/c2f1c7cab3fbd06661f0e42c46859d2c.html