我是PHP的新手,并且一直在为我的网站制作登录系统。我不确定如何处理当前代码的会话,我只是在寻找一些如何做的建议。
这是我的用户类:
<?php
include_once('connection.php');
class User{
private $db;
public function __construct(){
$this->db = new connection();
$this->db = $this->db->dbConnect();
}
public function Login($username, $password){
if(!empty($username) && !empty($password)){
$st = $this->db->prepare("SELECT * FROM users WHERE username =? AND password=?");
$st->bindParam(1, $username);
$st->bindParam(2, $password);
$st->execute();
if($st->rowCount() == 1){
header('location: userHome.php');
}
else{
echo "Incorrect username or password";
}
}
else{
echo "Please enter your username and password";
}
}
public function Register($username, $password, $email){
if(!empty($username) && !empty($password) && !empty($email)){
$st = $this->db->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$st->bindParam(1, $username);
$st->bindParam(2, $password);
$st->bindParam(3, $email);
$result = $st->execute();
if($result){
echo("Success. You have been registered");
}
else{
echo("There has been a problem. Please try again");
}
}
else{
echo "Please fill in all of the fields";
}
}
}
?>
这是我的连接类:
<?php
class connection{
private $db_host = 'omitted',
$db_name = 'omitted',
$db_username = 'omitted',
$db_pass = 'omitted';
public function dbConnect(){
try
{
return new PDO("mysql:host=".$this->db_host.';dbname='.$this->db_name,
$this->db_username, $this->db_pass);
}
catch(PDOException $e){
$e->getMessage();
}
}
}
?>
这是我的index.php文件,用户登录:
<?php
include_once('user.php');
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$object = new User();
$object->Login($username, $password);
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/layout.css">
</head>
<body>
<div id="form-container">
<h2>Login</h2>
<form method="post" action="index.php">
<label for='username'>Username: </label>
<input type="text" name="username"/><br>
<label for='password'>Password: </label>
<input type="password" name="password"/><br>
<input type="submit" value="Submit" id="button" name="submit"/>
</form>
<br>
<a href="register.php">Register Here</a>
</div>
</body>
</html>
我一直坚持如何使用我当前的代码解决处理会话一段时间,并且非常感谢任何建议。
谢谢。
答案 0 :(得分:2)
好的,我首先会在user.class.php和index.php的顶部添加一个会话开始。要防止多次调用session_start()
,请使用以下代码:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
在您的登录功能中:
if($st->rowCount() == 1){
$_SESSION['login'] = 'true';
$_SESSION['username'] = $username;
header('location: userHome.php');
}
您可以轻松访问index.php页面并仅显示已登录用户的内容:
if($_SESSION['status'] == 'true') {
echo 'Username: <b>'.$_SESSION['username'].'</b>';
} else {
//your login form
}
在我的代码中,我还将电子邮件保存到会话变量中,如果您希望可以从数据库中查询用户的电子邮件。
顺便说一下,为了检查是否提交了帖子,我建议您使用:(reference)
if($_SERVER['REQUEST_METHOD'] == 'POST')