I was going to append this to one of my articles on anti-sql injection but as this may undergo some revisions, I'll give it it's own page.

The following PHP code accepts a username and password login and demonstrates how to check against the database without including text that the website visitor submits.

We're simply going to accept both the username and password, then lookup the username in the database, retrieving the values we need. This script will apply to sites where the username is alphanumeric (no symbols, punctuation allowed) and where the password is any string (so lots of special characters, possible injection likely).

I want to put the basic code that I use quite a lot as a note:


if (!mysqli_connect_errno()) {
        if (isset($_POST['myUsername'])&&($_POST['myUsername']!="")) {

                // reduce username to alphanumerics (shouldn't have symbols anyway)
                $this_username_cred = preg_replace("/[^a-zA-Z0-9]+/", "", $_POST['myUsername']);
                $this_username_cred = mysqli_real_escape_string($connect, $this_username_cred);

                // store submitted password (and encrypt as it would appear in the database)
                $this_password_cred = md5($_POST['myPassword']);

                // Check username exists and role is admin...
                $auth_uquery="SELECT user_name, user_role, password FROM users_table WHERE user_name='$this_username_cred'";

                // run the query: formatted usernames accepted only
                if ($auth_uresult = mysqli_query($connect, $auth_uquery, MYSQLI_USE_RESULT)) {

                        while($obj = $auth_uresult->fetch_object()){
                            $auth_user = $obj->user_name;
                            $auth_role = $obj->user_role;
                            $auth_pass = $obj->password;


                // Then compare to user-posted variables
                if (($auth_pass==$this_password_cred)&&($auth_user==$this_username_cred)&&($auth_role=="Administrator")) {
                        $error_msg='<b style="color:green">Request Approved!</b>';
                } else {
                        $error_msg='<b style="color:red">Request Denied!!!<br />Invalid username/password provided!</b>';

This way you are only checking the username is of a valid format (so if email, then only include characters an email can have). The password can be whatever and its value is never run against your database.

As always, not invincible, but much harder to get round.

Add comment