I am new to PHP and have been making a login system for my website. I am unsure of how I should be handling sessions with my current code, and am just looking for some advice on how to do so.
Here is my User class:
<?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";
}
}
}
?>
And here is my connection class:
<?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();
}
}
}
?>
And here is my index.php file where the user logs in:
<?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>
I have been stuck on how to tackle handling sessions with my current code for a while now, and any suggestions will be much appreciated.
Thank you.