Jacobs "Blog"

PHP Login Script

This is a simple PHP login script that you can use in your simple applications. I have also included a 'register' script which creates a username/password record in a database.

The Database

create database users (userid int not null auto_increment, username varchar(250) not null, password varchar(250) not null, primary key(userid));

The PHP

    <?php
    // We'll be working with the session, so let's start the session
    session_start();

    /* 
     * Let's build some functions!
     */
    function clogin($username, $password, $pdo)
    {
            $p = $pdo->prepare("SELECT password FROm users WHERE username = :un");
            $p->execute([':un' => $username]);
            $p = $p->fetch();

            if (password_verify($password, $p[0]))
            {
                    return 1;
            } else {
                    return 0;
            }
    }

    function cregister($username, $password, $pdo)
    {
            $password = password_hash($password, PASSWORD_BCRYPT);
            $r = $pdo->prepare("INSERT INTO users (username, password) VALUES (:un, :pw)");
            $r->bindParam(":un", $username);
            $r->bindParam(":pw", $password);

            if ($r->execute())
            {
                    return 1;
            } else {
                    return 0;
            }
    }

    /*
     * Database Connection
     */

    try
    {
            $db = new PDO("mysql:host=localhost;dbname=test", 'test', 'testpass123');
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
            die($e->getMessage());
    }

    /*
     * Do stuff
     */

    $records = array(
            array("user1", "userpass1"),
            array("user2", "userpass2"),
            array("user3", "userpass3"),
            array("user4", "userpass4")
    );

    foreach ($records as $rec)
    {
            if (cregister($rec[0], $rec[1], $db))
            {
                    echo "<p>Registered $rec[0] with pass $rec[1]</p>";
                    if (clogin($rec[0], $rec[1], $db))
                    {
                            echo "<p>Logged into $rec[0] with $rec[1]</p>";
                    } else {
                            echo "<p>Could not log into $rec[0] with $rec[1]</p>";
                    }
            } else {
                    echo "<p>Could not register $rec[0] with pass $rec[1]";
            }
    }

~
~

Some Explaining

We create the simple 'users' table. The PHP script will hash a provided password and create a record for that user.

You will notice that the hash changes every single time; my total understanding of this is that the salt is changed, and password_verify has some way of understanding this. For people like me, creating simple apps to do simple jobs, this is more than enough to know.

You can see the table below after I ran the php script twice:

MariaDB [(none)]> select * from test.users;
+--------+----------+--------------------------------------------------------------+
| userid | username | password                                                     |
+--------+----------+--------------------------------------------------------------+
|      1 | user1    | $2y$10$ShMthkUGzjl2tOY1jV3D8Onax.P8QliW/chNwuNgjqXDgAwS466xK |
|      2 | user2    | $2y$10$.oPuXVOOrgn3ppg99hflveytNLLQGMpbpgDr.Mqyfi/c1nmzobf5. |
|      3 | user3    | $2y$10$mUVO8OVYx3dTStPxen1lCeLtX4IDP0sxLdW42LTT6IAvnYd7GWl.K |
|      4 | user4    | $2y$10$eDaC4uzx4nE1uDdIgaeOBuKfv0rC1H4MDrfzawpoj5S/PZLy6IJze |
|      5 | user1    | $2y$10$ggqFzaylX1Xh/Z.zL.HwoOyRW1783mm2XefrTbZ17cw2aMlInm/5C |
|      6 | user2    | $2y$10$ysE5y5Bt/K8DdwFEL1VrvOawyVYrH3QGLJpQRM5kpNE6ZYPGdn8jm |
|      7 | user3    | $2y$10$l0jwQhDXegfnJfUMqVuv/eBCvj5.j8OYhqSIS8A6YA5s7T1ynoofG |
|      8 | user4    | $2y$10$qcvr59c4CPMbnWzJbFzjuuHE4an.OVRs9tpePKI/rdG3wEuDUI0Hm |
+--------+----------+--------------------------------------------------------------+
8 rows in set (0.001 sec)

Something I will have to do when I have a little more time is to find out exactly which user1 it's logging into. Something I should try do pretty soon.

Also I have not setup any kind of logic for knowing that a user has logged in outside of this script using sessions. I'll do this some other time.


Image from: https://www.btricks.in/