0

又要开始了!

我有一个用于登录的表单。

<form method="post" action="user.php">

<label>Username:</label><label class="error"><?php echo $form->error("username"); ?></label>
<input type="text" name="username" maxlength="25" class="text" value="<?php echo $form->value("username"); ?>"/>

<label>Password:</label><label class="error"><?php echo $form->error("password"); ?></label>
<input type="password" name="password" value="<?php echo $form->value("password"); ?>" class="text" />

<input type="submit" name="login" class="button" value="Login" />

这是我的 user.php 文件

class User {

public function __construct() {

    $this->db = new Database(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);

}

public function login() {

    //check username for errors
    $user = $_POST['username'];

    $field = "username";

    //check username isn't empty
    if (empty($user)) {
        $form->setError($field, "* Username not entered");
    }
    //username taken
    else {
        $query = $this->db->select("SELECT userid FROM user WHERE username = :username", array('username' => $user));
        if (!$query) {
            $form->setError($field, "*Username not found");
        }
    }

    //check passwords for error
    $pass = $_POST['pass'];

    $field = "pass";

    //check password isn't empty
    if (empty($pass)) {
        $form->setError($field, "*Password not entered");
    }
    //incorrect password
    else {
        $query = $this->db->select("SELECT userid FROM user WHERE username = :username AND password = :password", array('user' => $user, 'password' => Hash::create('sha256', $pass, HASH_PASSWORD_KEY)));
        if (!$query) {
            $form->setError($field, "*Password not found");
        }
    }

    //if errors exist, return to user - otherwise insert into db
    if ($form->num_errors > 0) {
        return 1;  //Errors with form
    } 
    else{

        //use the userid and set it as session variable
        $query = $this->db->select("SELECT userid FROM user WHERE username = :username AND password = :password", array('user' => $user, 'password' => Hash::create('sha256', $pass, HASH_PASSWORD_KEY)));
        $_SESSION['userid'] = $query[0]['userid'];

        $_SESSION['logged_in'] = true;

        header("Location ".URL."dashboard.php");
    }
}
}

如您所见,我使用$form的是 form.php。

从表单本身访问此类的最佳方法是什么?

谢谢。

4

1 回答 1

4
if(isset($_POST['login'])){
    $this->login();
}
if(isset($_POST['register'])){
    $this->register();
}
else{
    $this->logout();
}

注销将始终被执行。这是因为 $_POST['register'] 没有设置,总是采用 else 条件。将第二个更改ifelse if.

于 2013-04-15T05:16:00.290 回答