重新开始!
我有一张用于登录的表单。
<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.php中的$form
。
从表单本身访问此类的最佳方法是什么?
感谢。
答案 0 :(得分:4)
if(isset($_POST['login'])){
$this->login();
}
if(isset($_POST['register'])){
$this->register();
}
else{
$this->logout();
}
注销将始终执行。这是因为没有设置$ _POST ['register'],并且总是采用else条件。将第二个if
更改为else if
。