# Website Login Form Help!



## censored (Apr 1, 2014)

Hi,

I am trying to get my website up and running with a required login form to access the site.
I currently have all the pages up and connected to my server but the login form will not output the necessary information to be received by the SQL database.

I need help with the PHP/SQL coding to reflect the data I am trying to send/receive. I enter my information from the login form and when it submits it takes me to the verification page for the data and it gives me an error report saying that no data was received.

Website: http://utulocal577.is-great.org/index.php

I am using Dreamweaver.

Thanks


----------



## colinsp (Sep 5, 2007)

Without seeing the code there is little we can do. Post it here.


----------



## censored (Apr 1, 2014)

There is a lot of code and I do no know from what I should post. I don't want to flood the forum with lengthy code postings.


----------



## JiminSA (Dec 15, 2011)

specifically we need to see the code in includes/process_login.php


----------



## censored (Apr 1, 2014)

Code for the login processing(process_login.php):

<?php
include_once 'includes\db_connect.php';
include_once 'includes\functions.php';

sec_session_start(); // Our custom secure way of starting a PHP session.

if (isset($_POST['union_id'], $_POST['p'])) {
$union_id = $_POST['union_id'];
$password = $_POST['p']; // The hashed password.

if (login($union_id, $password, $mysqli) == true) {
// Login success 
header('Location: ../utulocal577.html');
} else {
// Login failed 
header('Location: ../index.html?error=1');
}
} else {
// The correct POST variables were not sent to this page. 
echo 'Invalid Request';
}
?>


----------



## JiminSA (Dec 15, 2011)

OK now we need the index.html and the utulocal577.html listings ...
(When you reply please use the "Go Advanced" so that you can post your code properly, using the <> button ...)


----------



## censored (Apr 1, 2014)

These should be all the coding pages that has any communication with the login page:

*(Index.php)*

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php
include_once 'includes\db_connect.php';
include_once 'includes\functions.php';

if (login_check($mysqli) == true) {
    $logged = 'in';
} else {
    $logged = 'out';
}

?>

	<?php
        if (isset($_GET['error'])) {
            echo '

Error Logging In!

';
        }
        ?> 
		[IMG]United%20Transportation%20Union_files/loginlogo.jpg[/IMG]
		Enter your Union ID and Password to access your UTU Local 577 Account

        [IMG]United%20Transportation%20Union_files/user-icon.png[/IMG]</a>

		[IMG]United%20Transportation%20Union_files/pass-icon.png[/IMG]

Forget Your Union ID or Password?
```
*(db_connect.php)*

```
<?php
include_once 'includes\psl-config.php';   // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
?>
```
*(psl-config.php)*

```
<?php
/**
 * These are the database login details
 */  
define("HOST", "localhost");     // The host you want to connect to.
define("USER", "root");    // The database username. 
define("PASSWORD", "xxxxxxxxx");    // The database password. 
define("DATABASE", "secure_login");    // The database name.

define("CAN_REGISTER", "any");
define("DEFAULT_ROLE", "member");

define("SECURE", FALSE);    // FOR DEVELOPMENT ONLY!!!!
?>
```
*(functions.php)*

```
<?php
include_once 'includes/psl-config.php';

function sec_session_start() {
    $session_name = 'union_id_login';   // Set a custom session name
    $secure = SECURE;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id();    // regenerated the session, delete the old one. 
}

function login($union_id, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, union_id, username, email, password, salt
        FROM members
       WHERE union_id = ?
        LIMIT 1")) {
        $stmt->bind_param('s', $union_id);  // Bind "$union_id" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $union_id, $db_password, $salt);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts

            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $union_id = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $union_id);
                    $_SESSION['union_id'] = $union_id;
                    $_SESSION['login_string'] = hash('sha512', 
                              $password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', '$now')");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time 
                             FROM login_attempts [CODE]
                             WHERE user_id = ? 
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}
function login_check($mysqli) {
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], 
                        $_SESSION['union_id'], 
                        $_SESSION['login_string'])) {

        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $union_id = $_SESSION['union_id'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM members 
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if ($login_check == $login_string) {
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&', '&', $url);
    $url = str_replace("'", ''', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

?>
```
*(forms.js)*

```
function formhash(form, password) {
    // Create a new element input, this will be our hashed password field. 
    var p = document.createElement("input");
 
    // Add the new element to our form. 
    form.appendChild(p);
    p.name = "p";
    p.type = "hidden";
    p.value = hex_sha512(password.value);
 
    // Make sure the plaintext password doesn't get sent. 
    password.value = "";
 
    // Finally submit the form. 
    form.submit();
}
 
function regformhash(form, id, union_id, password) {
     // Check each field has a value
    if (  union_id.value == ''     || 
          password.value == '') {
 
        alert('You must provide all the requested details. Please try again');
        return false;
    }
 
    // Check the username
 
    re = /^\w+$/; 
    if(!re.test(form.union_id.value)) { 
        alert("Union ID must contain only letters, numbers and underscores. Please try again"); 
        form.union_id.focus();
        return false; 
    }
 
    // Check that the password is sufficiently long (min 6 chars)
    // The check is duplicated below, but this is included to give more
    // specific guidance to the user
    if (password.value.length < 6) {
        alert('Passwords must be at least 6 characters long.  Please try again');
        form.password.focus();
        return false;
    }
 
    // At least one number, one lowercase and one uppercase letter 
    // At least six characters 
 
    var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/; 
    if (!re.test(password.value)) {
        alert('Passwords must contain at least one number, one lowercase and one uppercase letter.  Please try again');
        return false;
    }
 
   
 
    // Create a new element input, this will be our hashed password field. 
    var p = document.createElement("input");
 
    // Add the new element to our form. 
    form.appendChild(p);
    p.name = "p";
    p.type = "hidden";
    p.value = hex_sha512(password.value);
 
    // Make sure the plaintext password doesn't get sent. 
    password.value = "";
 
    // Finally submit the form. 
    form.submit();
    return true;
}
```


----------



## JiminSA (Dec 15, 2011)

Try changing the header location links to .php from .html and see what transpires ...


----------



## censored (Apr 1, 2014)

I don't think it would be that because all pages linked to the login process are already PHP and I don't have any PHP code (yet) on those sites. I need to figure out if my SQL commands are working with my PHP but I cannot find where this miscommunication in the code is.

I enter both fields correctly and when I submit the query it goes to process_login.php and goes through the code and comes back with the NEGATIVE function which sends me back to the login page with an error. Then I submit it again and it goes to 'Invalid Request' which is the function for a blank form or the sql query never sent.


----------



## dukevyner (Nov 4, 2011)

> ```
> function login($union_id, $password, $mysqli) {
> // Using prepared statements means that SQL injection is not possible.
> if ($stmt = $mysqli->prepare("SELECT id, union_id, username, email, password, salt
> ...


 why is the id = ? I'm no expert, but i've done a php login and this is confusing to me. all "where (union_/member_/ )id =" are ? why. sorry if this is simple i just haven't seen it before

-Luke


----------



## JiminSA (Dec 15, 2011)

Luke, this may help you understand the ? and the associated bind ...


----------



## NegativeKelvin (Apr 12, 2012)

a while back I came across a project on github for scalable, integratable PHP login framework. The project is located here: http://www.php-login.net/


----------



## JiminSA (Dec 15, 2011)

censored - check your db entry hasn't reached the failed login max and think about changing this code if ($stmt->num_rows == 1) to cater for duplicates (>= 1). Both unmet conditions will produce the response you receive.
Also check how $login_string is set up as a session variable in case that is the problem area...


----------

