0

Okay, on my local dev server I can login with my simple form on index.php. it will redirect me to admin.php because my username and password has matched that in the database.

However when I upload this to my live server it doesn't work. I don't understand. To create the username and password in the database I use new_admin.php. Then using index.php i login which willa cces my functions from functions.php.

functions.php:

//*****************************************************************/
//mysql_prep();
//
function mysql_prep($string) {
    global $connection;

    $escaped_string = mysqli_real_escape_string($connection, $string);
    return $escaped_string;
}



//*****************************************************************/
//confirm_query();
//
function confirm_query($result_set) {
    if (!$result_set) {
        die("Database query failed.");
    }
}








//////////////LOG IN FUNCTIONS
/////////////////////////////////////////////////////////////////////////



//*****************************************************************/
//password_encrypt();
//

        function password_encrypt($password) {
            $hash_format = "$2y$10$";   // Tells PHP to use Blowfish with a "cost" of 10
            $salt_length = 22;                  // Blowfish salts should be 22-characters or more
            $salt = generate_salt($salt_length);
            $format_and_salt = $hash_format . $salt;
            $hash = crypt($password, $format_and_salt);
            return $hash;
        }               



//*****************************************************************/
//generate_salt();
//
        function generate_salt($length) {
          // Not 100% unique, not 100% random, but good enough for a salt
          // MD5 returns 32 characters
          $unique_random_string = md5(uniqid(mt_rand(), true));

            // Valid characters for a salt are [a-zA-Z0-9./]
          $base64_string = base64_encode($unique_random_string);

            // But not '+' which is valid in base64 encoding
          $modified_base64_string = str_replace('+', '.', $base64_string);

            // Truncate string to the correct length
          $salt = substr($modified_base64_string, 0, $length);

            return $salt;
        }



//*****************************************************************/
//password_check();
//
    function password_check($password, $existing_hash) {
        // existing hash contains format and salt at start
      $hash = crypt($password, $existing_hash);
      if ($hash === $existing_hash) {
        return true;
      } else {
        return false;
      }
    }



//*****************************************************************/
//find_admin_by_username();
//
    function find_admin_by_username($username) {
        global $connection;

        $safe_username = mysqli_real_escape_string($connection, $username);

        $query  = "SELECT * ";
        $query .= "FROM admins ";
        $query .= "WHERE username = '{$safe_username}' ";
        $query .= "LIMIT 1";
        $admin_set = mysqli_query($connection, $query);
        confirm_query($admin_set);
        if($admin = mysqli_fetch_assoc($admin_set)) {
            return $admin;
        } else {
            return null;
        }
    }



//*****************************************************************/
//attempt_login();
//
    function attempt_login($username, $password) {
        $admin = find_admin_by_username($username);
        if ($admin) {
            // found admin, now check password
            if (password_check($password, $admin["hashed_password"])) {
                // password matches
                return $admin;
            } else {
                // password does not match
                return false;
            }
        } else {
            // admin not found
            return false;
        }
    }       



//*****************************************************************/
//logged_in();
//
    function logged_in() {
        return isset($_SESSION['admin_id']);
    }



//*****************************************************************/
//confirm_logged_in();
//
    function confirm_logged_in() {
        if (!logged_in()) {
            redirect_to("index.php");
        }
    }

new_admin.php:

<?php 
session_start();
require_once("includes/db_connection.php");
require_once("includes/functions.php");
?>

<html>
<head>
</head>
<body>

<?php 

if(isset($_POST['submit'])){

    $username = mysql_prep($_POST["username"]);
    $hashed_password = password_encrypt($_POST["password"]);

    $query  = "INSERT INTO admins (";
    $query .= "  username, hashed_password";
    $query .= ") VALUES (";
    $query .= "  '{$username}', '{$hashed_password}'";
    $query .= ")";
    $result = mysqli_query($connection, $query);

    if ($result) {
      // Success
      $_SESSION["message"] = "Admin created.";
      redirect_to("admin.php");
    } else {
      // Failure
      $_SESSION["message"] = "Admin creation failed.";
    }

}


?>
<form action="new_admin.php" method="post">
    username:
<input type="text" name="username"/><br/>
    password:
<input type="password" name="password"/></br>
<input type="submit" name="submit"/>


</form>

index.php:

 <?php 
 session_start();
 require_once("includes/db_connection.php");
 require_once("includes/functions.php");
 ?>



<?php
 $username = "";

if (isset($_POST['submit'])) {
// Process the form
    $username = $_POST["username"];
    $password = $_POST["password"];

    $found_admin = attempt_login($username, $password);

if ($found_admin) {
  // Success
        // Mark user as logged in
        $_SESSION["admin_id"] = $found_admin["id"];
        $_SESSION["username"] = $found_admin["username"];
  redirect_to("admin.php");
} else {
  // Failure
  $_SESSION["message"] = "Username/password not found.";
}

} else {
// This is probably a GET request

} // end: if (isset($_POST['submit']))

?>




<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Test</title>
</head>
<body>
  <?php 
    if(isset($_SESSION['message'])){
      echo $_SESSION['message'];
    }
  ?>
    <h1>Login</h1>
    <form action="index.php" method="post">
        <p>Username:
            <input type="text" name="username" value="" />
        </p>
        <p>Password:
            <input type="password" name="password" value="" />
        </p>
        <input type="submit" name="submit" value="Submit" />
    </form>

I know that i am putting in the correct login username and password but all i get is "Username/password not found." from my session error message.

Any ideas why this is happening?

EDIT:

Ive just noticed that i am not getting the error "Username/password not found" So this means that my attempt_login() function must be returning true. doesnt it?

  • What version of PHP's on the LIVE server? Plus, is the column long enough to accomodate the hash? Add error reporting to the top of your file(s) right after your opening ` – Funk Forty Niner Jan 26 '15 at 15:03
  • Done any basic debugging, like putting in some debug output to track down the exact execution path? Check what the queries you're building look like? Checked their results when you run them manually? – Marc B Jan 26 '15 at 15:08
  • 1
    **[DANGER! You need to prevent SQL Injection!](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)** – Jay Blanchard Jan 26 '15 at 15:10
  • the column is long enough as it is the same as on my dev server (60) characters. i will check with error_reporting now and see if it returned anything – matthew smart Jan 26 '15 at 15:11
  • @marc B , i didnt think i needed to as it worked on my dev server – matthew smart Jan 26 '15 at 15:11
  • I have seen a case not long ago where 60 wasn't enough. Try 75 just to be sure. I always use 255 for future cases where it is suggested to use. MySQL will *probably* fail silently if the column isn't long enough. – Funk Forty Niner Jan 26 '15 at 15:17
  • i have changed to 255 and its not that – matthew smart Jan 26 '15 at 15:22
  • You have `redirect_to("admin.php");` yet you show that the admin page is called new_admin.php - that's all I can make of this. Your form action is also `new_admin.php` – Funk Forty Niner Jan 26 '15 at 15:33
  • new_admin.php is a seperate page from admin.php. admin.php is where i should get redirected to and new_admin.php is to create a new admin – matthew smart Jan 26 '15 at 15:35
  • I don't know what else to say. Doublet/triple check your DB name, table, columns (types, lengths etc), uploaded files, server cache (could be sessions related). Use `var_dump();` - `var_dump($variable_to_check);` is all I can suggest and see what's going through or not. – Funk Forty Niner Jan 26 '15 at 15:37
  • I think I got something like this not long ago. I mean, on my localhost the session was going ok, so I imported all to the live server (a free one, as many other times) and that time I couldn't log in. As it was a free online server, I could create another hosting, uploaded it again, and worked fine, with the same database, php... was strange. Was checking it all always and username/password were ok. – Zander Jan 26 '15 at 15:38
  • Try adding `global $connection;` to `attempt_login()` function. It's in one function but not that one. Same for `password_check()` and possibly others. – Funk Forty Niner Jan 26 '15 at 15:42
  • Made any progress with the new comments? – Funk Forty Niner Jan 26 '15 at 16:19
  • only just this minute, it was because output buffering wasnt turned on i think. As everything was passing from debugging, literally everything. And when i went to admin.php it would say that iw as logged in , which meant it was the redirect which wasnt working. Output buffering was on in my dev server so worked but wasnt on the server. So when i actually used javascript window.location it redirected me fine and worked. – matthew smart Jan 26 '15 at 16:24
  • That's great Matthew, glad to hear it. *Cheers!* You can place your own answer too. Stack lets you do that. *The choice is yours.* – Funk Forty Niner Jan 26 '15 at 16:25

0 Answers0