Skip to content

Instantly share code, notes, and snippets.

@codehakase
Created June 14, 2017 06:24
Show Gist options
  • Save codehakase/fb18e628c65c37b0c10126ec818e0161 to your computer and use it in GitHub Desktop.
Save codehakase/fb18e628c65c37b0c10126ec818e0161 to your computer and use it in GitHub Desktop.
Login Script -OOP
<?php
/**
* User class
* Database Driver - PDO
*/
class User
{
private $db; //your database handler
public function login(string $username, string $password)
{
// check if username exists in database
$check = $this->db->query("SELECT * FROM users WHERE username = '$username' OR email = '$username')->fetchObject();
if ($check) {
// verify password
if (password_verify($password, $check->password) {
// generate your sessions here
header("Location: dashboard/index");
} else {
// error handling
}
}
}
}
/**
* Using the class in a view
*/
if (isset($_POST['login']) {
$user = new User; // initalize the User object
$username = $_POST['username'];
$password = $_POST['password'];
$user->login($username, $password);
}
/**
* Procedural style
*/
.... other db crendials
if (isset($_POST['login']) {
$username = $_POST['username'];
$password = $_POST['password']
if (!empty($username) && !empty($password)) {
$check = $db->query("SELECT * FROM users WHERE username = '$username' OR email = '$username')->fetchObject();
if ($check) {
// verify password
if (password_verify($password, $check->password) {
// generate your sessions here
header("Location: dashboard/index");
} else {
// error handling
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment