我在 PHP 中的 OOP 中确实有一些代码应该登录/注册用户,并且注册功能效果很好,但是登录功能不起作用,我无法登录。而且我还注意到在数组中$_SESSION
我有未定义的索引“登录”、“密码”。这是主页:
<?php
require_once "libs/user_class.php";
$user = User::getObject();
$auth = $user->isAuth();
if(isset($_POST["reg"])){
$login = $_POST["login"];
$password = $_POST["password"];
$reg_success = $user->regUser($login,$password);
}
elseif (isset($_POST["auth"])){
$login = $_POST["login"];
$password = $_POST["password"];
$auth_success = $user->login($login,$password);
if($auth_success){
header("Location:index.php");
exit;
}
}
?>
<html>
<head>
<title>REGISTER</title>
</head>
<body>
<?php
if($auth){
echo "Welcome".$_SESSION["login"];
}
else{
echo '<h2>REGISTRATION</h2>
<form action="index.php" method = "post" name="reg">
<table>
<tr>
<td>Log in</td>
<td>
<input type="text" name = "login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name = "password" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type="submit" name="reg" value = "register" />
</td>
</tr>
</table>
</form>
<h2>LOGIN</h2>
<form action="index.php" method = "post" name="auth">
<table>
<tr>
<td>Log in</td>
<td>
<input type="text" name = "login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name = "password" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type="submit" name="auth" value = "authorize" />
</td>
</tr>
</table>
</form>';
}
?>
</body>
</html>
和 user_class.php:
<?php
class User{
private $db;
private static $user = null;
private function __construct(){
$this->db = new mysqli("localhost", "root", "root", "temp");
$this->db->query("SET NAMES 'utf8'");
}
public static function getObject(){
if(self::$user === null) self::$user = new User();
return self::$user;
}
public function regUser($login, $password){
if($login == "")return false;
if($password == "")return false;
$password = md5($password);
return $this->db->query("INSERT INTO `users` (`login`, `password`) VALUES ('$login','$password')");
}
private function checkUser($login, $password){
$result_set = $this->db->query("SELECT `password` FROM `users` WHERE `login` = '$login'");
$user = $result_set->fetch_assoc();
$result_set->close();
if(!$user) return false;
return $user["password"] === $password;
}
public function isAuth(){
session_start();
$login = $_SESSION["login"];
$password = $_SESSION["password"];
return $this->checkUser($login,$password);
}
public function login($login, $password){
if($this->checkUser($login, $password)){
session_start();
$_SESSION["login"] = $login;
$_SESSION["password"] = $password;
return true;
}
else return false;
}
public function __destruct(){
if ($this->db) $this->db->close();
}
}
?>