1

I am trying to build a basic website that can access a mysql database. When I was hosting it on my local wamp server, everything worked perfectly, but now that I have posted it online, I am having an issue. When visiting the log in page on a browser for the first time (or in incognito mode) the user must log in twice before being permitted access.

I was able to find someone dealing with the same issue (Problems with PHP, MySQL based log-in system), but after changing the URL the form posts to (using "loginchecker.php" as well as the whole URL including http://.), I was still encountering the problem. The first set of code is my index.php file and the second is the page that verifies the user's log in credentials. Also just as a sidenote, this is mostly a learning experience for me, so I'm not concerned about security loopholes for now. Thanks in advance for any help!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>My Log In</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link href="css/styles.css" rel="stylesheet">
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js">        </script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js">    </script>
    <![endif]-->
</head>

<body>
    <script src="js/jquery.js"></script>
    <script src="js/bootstrap.js"></script>

    <div id="wrapper">
    <h1>Login</h1>
    <br />
    <form id="form" action="loginchecker.php" method="post" enctype="multipart/form- data">
    Username: <input type="text" name="username" /> <br /><br />
    Password: <input type="password" name="password" /> <br /><br />
    <input type="submit" value="Login" name="Submit" />
    </form>
</body>
</html>

And the second page:

<?php
session_start();

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

include_once("dbconnect.php");

$usname = strip_tags($_POST["username"]);
$paswd = strip_tags($_POST["password"]);

$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);

$sql = "SELECT id, username, password FROM members WHERE username = '$usname' AND activated = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[1];
$dbPassword = $row[2];


// Check if the username and the password they entered were correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
    // Set session variables
    $_SESSION['username'] = $usname;
    $_SESSION['id'] = $uid;
    date_default_timezone_set('America/New_York');
    $date = date("Y/m/d");
    $time = date("H:i:s");
    $in = 'in';
    // Log the user's successful log in to the database
    $toLog = "INSERT INTO accesslog (UserID, Username,  Date, Time) VALUES ('". $_SESSION['id'] ."', '". $_SESSION['username'] ."', '". $date ."', '". $time. "')";
    mysqli_query($dbCon, $toLog);
    // Now direct to users feed
    echo '<meta http-equiv="refresh" content="0.2; URL=user.php" />';
    header("Location: user.php");

} else {
    echo "Oops that username or password combination was incorrect. <br /> Please try again.";
}
}
?>
Community
  • 1
  • 1
  • 2
    remove `echo '';` and try again, because meta stuff gets cached in to the browser – meda Jul 09 '14 at 20:12
  • 1
    @meda - Agreed; it would also cause your header to fail (since you're outputting something before sending headers) – Chris Forrence Jul 09 '14 at 20:25
  • I removed the meta tag, but the problem persists. Without the meta tag it never redirected the page. I also tried changing the header to the full URL after removing the meta tag, but that did not help either. – user3821950 Jul 09 '14 at 20:47
  • @user3821950 is the insert successful when it does not redirect? – meda Jul 09 '14 at 20:54
  • @meda Yes, the insert works when the meta tag is not included. It also works when the meta tag is included whether it is the first log in attempt or the second. – user3821950 Jul 10 '14 at 13:19
  • @user3821950 well you need to display error, otherwise how would you know? `error_reporting(-1);` – meda Jul 10 '14 at 13:35
  • @meda Sorry--I'm relatively new to PHP. I added that to the code and it did not show any errors. I think I may have a logical issue in my code rather than a syntactical one. I thought the problem might be related to the POST or SESSION variables, but I cannot identify the problem. – user3821950 Jul 10 '14 at 14:11

1 Answers1

0

Try the following

<?php
session_start();
date_default_timezone_set('America/New_York');


if (isset($_POST['username'], 
          $_POST['password'], 
          $_SESSION['id'], 
          $_SESSION['username'])) {

include_once("dbconnect.php");

$sql = "SELECT id, username, password 
        FROM members 
        WHERE username = ? AND activated = '1' LIMIT 1";

$stmt = mysqli_prepare($dbCon, $sql);
mysqli_stmt_bind_param($stmt, 's', $_POST['username']);
mysqli_stmt_execute($stmt);
$row = mysql_fetch_assoc($stmt);

//check if password is correct
if ($_POST['password'] === $row['password']) {
    // Set session variables
    $_SESSION['username'] = $row['username'];
    $_SESSION['id'] = $row['id'];

    $date = date("Y/m/d");
    $time = date("H:i:s");

    // Log the user's successful log in to the database
    $toLog = 'INSERT INTO accesslog (`UserID`, `Username`, `Date`, `Time`) 
              VALUES (?, ?, ?, ?)';

    $stmt = mysqli_prepare($dbCon, $toLog);
    mysqli_stmt_bind_param($stmt, 'ssss', $_SESSION['id'], 
                                          $_SESSION['username'], 
                                          $date, 
                                          $time);
    if(mysqli_stmt_execute($stmt)){
         header('Location: user.php');
         exit();//very important
    }else{
        echo "An error Occured!! failed to execute()";
    }


} else {
    echo "Password is incorrect";
}
}
?>
meda
  • 45,103
  • 14
  • 92
  • 122
  • I tried that and when it got to loginchecker.php from index.php, it was just a white blank page. I also tried taking out the if(isset($_SESSION)) variable requirements and adding the function to report errors, but it still yielded nothing. – user3821950 Jul 10 '14 at 15:05
  • `loginchecker.php` is the script name for this code? I dont know what else to suggest other than print errors so you can debug it, dont try to guess anything, do anything you can to display errors – meda Jul 10 '14 at 15:40
  • loginchecker.php is the name for this code, yes. I will try that for a while, and I will be sure to let you know if I find a solution. Thanks for your help. – user3821950 Jul 10 '14 at 15:44
  • like open a new php script and just mispell a function and get it to display errors check this http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php – meda Jul 10 '14 at 15:46
  • I didn't realize that my errors would be sent to their own file on my web server. I found that now. Plot twist: I tried hosting on a new server and it didn't work. When I added `error_reporting(E_ALL);` everything suddenly worked exactly as expected for no apparent reason. – user3821950 Jul 10 '14 at 16:16