PHP OOP Login Class

PHP OOP Login Class

The PHP OOP login code comes in two parts. One file is the class that connects to the database while the main file uses PDO objects to select and insert data.

Here is rundown of how it works. You have two main conditions; you have posted a login or you have not. If you post data by logging in, you will be successful or not. The code creates output based on success and failure.

Now, if there are no posted variables, you will either have a valid session or not. Validity is checked by matching the unix timestamp of your session variable against that of the value in the database. This way, only a valid timestamp will allow you to access sensitive code. Since PHP is more secure on some servers than others, this approach to check is taken.

Main File

include("class-login-PDO-form.php");
session_start();
$_SESSION['id'] = $_SESSION['id'];
$_SESSION['login'] = $_SESSION['login'];
$_SESSION['timestamp'] = $_SESSION['timestamp'];

$login = new Login();
$db = $login->db_connect();

//var_dump($db);
$username = array();
$password = array();
$myarray = array();
$myuser = array();
$mytime = array();
$my_check = array();

if ($_POST['username'] && $_POST['password']) {

    ##QUERY Sample#1
//$username = mysql_real_escape_string($_POST['username']);
//$password = mysql_real_escape_string($_POST['password']);
//$command = $db->prepare("SELECT * FROM logins_test WHERE login ='$username' AND password = password('$password')");

    ##QUERY Sample#2
    $username = $_POST['username'];
    $password = $_POST['password'];
    $command = $db->prepare("SELECT * FROM logins_test WHERE login =:login AND password = password(:password)");
    $command->bindParam(':login', $username);
    $command->bindParam(':password', $password);
    $command->execute();
    $result = $command->fetchAll();

    foreach ($result as $row) {
        $my_array[] = $row;
    }

    if (!empty($my_array)) {
        $_SESSION['id'] = $my_array[0]['id'];
        $_SESSION['login'] = $my_array[0]['login'];
        $_SESSION['timestamp'] = time();
        echo $_SESSION['id'] . " - " . $_SESSION['login'] . " - " . $_SESSION['timestamp'];
        echo "<br/>Success<br/>";

        $mytime = $_SESSION['timestamp'];
        $myuser = $_SESSION['id'];
        $command = "INSERT INTO logins_validate VALUES (NULL,:user_id, :time_current)";
        $command1 = $db->prepare($command);
        $command1->bindParam(':user_id', $myuser);
        $command1->bindParam(':time_current', $mytime);
        $command1->execute();

    } else {
        echo "Wrong username or password!";
    }
} else {
##VERIFY SESSION

    $mytime = $_SESSION['timestamp'];
    $myuser = $_SESSION['id'];

    $command = $db->prepare("SELECT * FROM logins_validate WHERE user_id =:login AND time_check = :mytime");
    $command->bindParam(':login', $myuser);
    $command->bindParam(':mytime', $mytime);
    $command->execute();
    $result = $command->fetchAll();

    foreach ($result as $row) {
        $my_check[] = $row;
    }

    if (!empty($my_check)) {
        echo "<br/>Session is validated!";
        ## ADD CUSTOM CODE HERE
    } else {
        echo "<br/>Session is not validated!";
        ## ADD CUSTOM CODE HERE
    }
}

echo "Is there an active session username: " . $_SESSION['login'];
echo "<br/>";
print_r($my_array);
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Username:<br/>
    <input type="text" name="username" value=""/><br/>
    Password:<br/>
    <input type="password" name="password" value=""/><br/>
    <input type="submit" name="submit"/>
</form>

Login Class

class Login
{
    private $host = "localhost";
    private $user = "username_goes_here";
    private $pw = "password_goes_here";
    private $database = "database_name_goes_here";

    /* function __construct()
    {

    }*/

    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }

}

Databases

The two databases used in this exercise can be created with code below.

CREATE TABLE IF NOT EXISTS `logins_test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `login` varchar(12) NOT NULL,
  `password` varchar(42) NOT NULL,
  `activation` varchar(40) DEFAULT NULL,
  `date_deactivated` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;




CREATE TABLE IF NOT EXISTS `logins_validate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `time_check` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

This simple tutorial has a very small class and lots of procedural code. Click this link if you want to see some more advanced PHP OOP Login classes.