Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 31, 2023 01:44
Show Gist options
  • Save code-boxx/957284646e7336ae01bb7a5e64f96022 to your computer and use it in GitHub Desktop.
Save code-boxx/957284646e7336ae01bb7a5e64f96022 to your computer and use it in GitHub Desktop.
PHP MYSQL User Login

PHP MYSQL USER LOGIN

https://code-boxx.com/simple-login-php-mysql/

NOTES

  1. Create a database and import 1-users.sql.
  2. Change the database settings to your own in 2-user-lib.php.
  3. Access 3-login.php in your web browser, and that's all. The dummy user account is jon@doe.com and the password is 123456.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `users` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`),
ADD UNIQUE KEY `user_email` (`user_email`);
ALTER TABLE `users`
MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT;
INSERT INTO `users` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
(1, 'Jon Doe', 'jon@doe.com', '$2y$10$eGdnkD1EcFdLmPtm0eqQ8OqjjRo6NWrXKDmbieFPKHmRUTmz7iYzi');
<?php
class Users {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = null;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET USER
function get ($id) {
$this->query(sprintf("SELECT * FROM `users` WHERE `user_%s`=?", is_numeric($id) ? "id" : "email"), [$id]);
return $this->stmt->fetch();
}
// (E) VERIFY EMAIL PASSWORD - SESSION MUST BE STARTED!
function login ($email, $password) {
// (E1) ALREADY SIGNED IN
if (isset($_SESSION["user"])) { return true; }
// (E2) GET USER
$user = $this->get($email);
if (!is_array($user)) { return false; }
// (E3) VERIFY PASSWORD + REGISTER SESSION
if (password_verify($password, $user["user_password"])) {
$_SESSION["user"] = [];
foreach ($user as $k=>$v) { if ($k!="user_password") { $_SESSION["user"][$k] = $v; }}
return true;
}
return false;
}
// (F) SAVE USER
function save ($name, $email, $pass, $id=null) {
// (F1) ADD/UPDATE SQL
if ($id===null) {
$sql = "INSERT INTO `users` (`user_name`, `user_email`, `user_password`) VALUES (?,?,?)";
$data = [$name, $email, password_hash($pass, PASSWORD_DEFAULT)];
} else {
$sql = "UPDATE `users` SET `user_name`=?, `user_email`=?, `user_password`=? WHERE `user_id`=?";
$data = [$name, $email, password_hash($pass, PASSWORD_DEFAULT), $id];
}
// (F2) PROCESS SAVE
$this->query($sql, $data);
return true;
}
}
// (G) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (H) CREATE USER OBJECT
$USR = new Users();
/* (A) ENTIRE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
/* (B) NOTIFICATION BAR */
#notify {
background: #ffd9e3;
padding: 10px;
margin-bottom: 10px;
}
/* (C) LOGIN FORM */
#login {
max-width: 400px;
border: 1px solid #ddd;
background: #f2f2f2;
margin: 0 auto;
padding: 20px;
}
#login h2 {
color: #6f6f6f;
padding: 0;
margin: 0 0 10px 0;
}
#login label, #login input {
width: 100%;
margin: 10px 0;
}
#login input {
padding: 10px;
}
#login input[type=submit] {
background: #4f69db;
color: #fff;
border: 0;
}
<?php
// (A) PROCESS LOGIN ON SUBMIT
session_start();
if (isset($_POST["email"])) {
require "2-user-lib.php";
$USR->login($_POST["email"], $_POST["password"]);
}
// (B) REDIRECT USER IF SIGNED IN
if (isset($_SESSION["user"])) {
header("Location: 4-index.php");
exit();
}
// (C) LOGIN FORM ?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" href="3-login.css">
</head>
<body>
<!-- (C1) ERROR MESSAGES (IF ANY) -->
<?php
if (isset($_POST["email"])) { echo "<div id='notify'>Invalid user/password</div>"; }
?>
<!-- (C2) LOGIN FORM -->
<form id="login" method="post">
<h2>MEMBER LOGIN</h2>
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Sign In">
</form>
</body>
</html>
<?php require "4-protect.php"; ?>
<!DOCTYPE html>
<html>
<head>
<title>DUMMY HOME PAGE</title>
</head>
<body>
<h1>Congrats! You have signed in.</h1>
<form method="post">
<input type="submit" name="logout" value="Logout">
</form>
</body>
</html>
<?php
// (A) "LISTEN" FOR LOGOUT
session_start();
if (isset($_POST["logout"])) { unset($_SESSION["user"]); }
// (B) REDIRECT TO LOGIN PAGE IF NOT SIGNED IN
if (!isset($_SESSION["user"])) {
header("Location: 3-login.php");
exit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment