article

Sunday, June 26, 2022

PHP Mysqli Login with OOP (Object-Oriented Programming)

PHP Mysqli Login with OOP (Object-Oriented Programming)

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Database Table 
CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(150) NOT NULL,
  `password` varchar(255) NOT NULL,
  `fullname` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `username`, `password`, `fullname`) VALUES
(1, 'cairocoders', '$2y$10$0qlCkQg4W97Sutj16Zg92uNssc2tAm6j2wIkiKvLlgMy2Td6dXGwC', 'Cairocoders Ednalan');

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.php
//index.php
<?php
	//start session
	session_start();
 
	//redirect if logged in
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login with OOP (Object-Oriented Programming)</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<section class="body">
    <div class="container"><h1 class="page-header text-center">PHP Mysqli Login with OOP (Object-Oriented Programming)</h1>
        <div class="login-box">
            <div class="row">
                <div class="col-12">
                    <div class="logo">
                        Cairocoders
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <br>
                    <h3 class="header-title">Login</h3>
					<form class="login-form" method="POST" action="login.php">
                        <div class="form-group">
							<input class="form-control" placeholder="Username" type="text" name="username" autofocus required>
                        </div>
                        <div class="form-group">
							<input class="form-control" placeholder="Password" type="password" name="password" required>
                            <a href="#!" class="forgot-password">Forgot Password?</a>
                        </div>
                        <div class="form-group">
                            <button type="submit" name="login" class="btn btn-lg btn-primary btn-block">Login</button>
                        </div>
                        <div class="form-group">
                            <div class="text-center">New Member? <a href="#!">Sign up Now</a></div>
                        </div>
                    </form>
				<?php //$password = "123456";
					//echo password_hash($password, PASSWORD_DEFAULT);
					if(isset($_SESSION['message'])){
						?>
							<div class="alert alert-info text-center">
								<?php echo $_SESSION['message']; ?>
							</div>
						<?php
	 
						unset($_SESSION['message']);
					}
				?>
                </div>
                
            </div>
        </div>
    </div>
</section>
<style>
@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,700&display=swap);

body {
    background: #f5f5f5;
}

.login-box {
    background-color:#fff; width:550px;
    background-position: center;
    padding: 50px;
    margin: 50px auto;
    min-height: 650px;
    -webkit-box-shadow: 0 2px 60px -5px rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 60px -5px rgba(0, 0, 0, 0.1);
}

.logo {
    font-family: "Script MT";
    font-size: 54px;
    text-align: center;
    color: #888888;
    margin-bottom: 50px;
}
.header-title {
    text-align: center;
    margin-bottom: 50px;
}
.login-form {
    max-width: 300px;
    margin: 0 auto;
}

.login-form .form-control {
    border-radius: 0;
    margin-bottom: 30px;
}

.login-form .form-group {
    position: relative;
}

.login-form .form-group .forgot-password {
    position: absolute;
    top: 6px;
    right: 15px;
}

.login-form .btn {
    border-radius: 0;
    -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;
}

.login-form .btn.btn-primary {
    background: #3BC3FF;
    border-color: #31c0ff;
}
</style>
</body>
</html>
login.php
//login.php
<?php
//start session
session_start();
 
include_once('User.php');
 
$user = new User();
 
if(isset($_POST['login'])){
	$username = $user->escape_string($_POST['username']);
	$password = $user->escape_string($_POST['password']);
 
	$auth = $user->check_login($username, $password);

	if(!$auth){
		$_SESSION['message'] = 'Invalid username or password';
    	header('location:index.php');
	}
	else{
		$_SESSION['user'] = $auth;
		header('location:home.php');
	}
}
else{
	$_SESSION['message'] = 'You need to login first';
	header('location:index.php');
}
?>
User.php
//DbConnection.php
<?php
class DbConnection{
 
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'devprojectdb';
 
    protected $connection;
 
    public function __construct(){
 
        if (!isset($this->connection)) {
 
            $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
 
            if (!$this->connection) {
                echo 'Cannot connect to database server';
                exit;
            }            
        }    
 
        return $this->connection;
    }
}
?>
User.php
//User.php
<?php
include_once('DbConnection.php');
 
class User extends DbConnection{
 
    public function __construct(){
 
        parent::__construct();
    }
 
    public function check_login($username, $password){
 
        $sql = "SELECT * FROM users WHERE username = '$username'";
        $query = $this- >connection- >query($sql);
 
        if($query- >num_rows  > 0){
            $row = $query- >fetch_array();
			if(password_verify($password, $row['password'])){
				return $row['id'];
			}else {
				return false;
			}		
        }
        else{
            return false;
        }
    }
 
    public function details($sql){
 
        $query = $this- >connection- >query($sql);
 
        $row = $query- >fetch_array();
 
        return $row;       
    }
 
    public function escape_string($value){
 
        return $this- >connection- >real_escape_string($value);
    }
}
home.php
//home.php
<?php
session_start();
//return to login if not logged in
if (!isset($_SESSION['user']) ||(trim ($_SESSION['user']) == '')){
	header('location:index.php');
}
 
include_once('User.php');
 
$user = new User();
 
//fetch user data
$sql = "SELECT * FROM users WHERE id = '".$_SESSION['user']."'";
$row = $user->details($sql);
 
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Mysqli OOP Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">PHP Mysqli OOP Login</h1>
	<div class="row">
		<div class="col-md-4 col-md-offset-4">
			<h2>Welcome to Homepage </h2>
			<h4>User Info: </h4>
			<p>Name: <?php echo $row['fullname']; ?></p>
			<p>Username: <?php echo $row['username']; ?></p>
			<p>Password: <?php echo $row['password']; ?></p>
			<a href="logout.php" class="btn btn-danger"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
		</div>
	</div>
</div>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
 
	header('location:index.php');
?>

Related Post