1

I am working on a simple login page which uses JS, JQuery and PHP.

login.php

<!DOCTYPE html>
<head>
    <title>Login activity to learn AJAX</title>
    <link rel="stylesheet" type="text/css" href="login.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="login.js"></script>
</head>
<body>
    <h1>AJAX learning</h1>
    <h2>Login below to continue</h2>
    <div class="row">
        <p>User ID:</p>
    </div>
    <div class="row">
        <p><input type="text" name="uid" id="usr"></p>
    </div>
    <div class="row">
        <p>Password:</p>
    </div>
    <div class="row">
        <p><input type="password" name="pwd"></p>
    </div>
    <div class="row">
        <p><input type="button" onclick="checkLogin()" value="Login"></p>
    </div>
    <div class="row">
        <p id="status"></p>
    </div>
</body>

login.js

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}
function checkLogin(){
    var xhttp=new ajaxRequest();
    var uid=$('input[name=uid]').val();
    var pwd=$('input[name=pwd]').val();
    xhttp.open("POST","do_login.php",true);
    xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var param = "UID="+uid+"&PASS="+pwd;
    xhttp.send(param);
    xhttp.onreadystatechange=function(){
        if(xhttp.readyState == 4){
            if(xhttp.status==200){
                generateResponse(xhttp.responseText,uid);
            }
            else{
                window.alert("Error while making request");
            }
        }
    }
}
function generateResponse(data,uid){
    if(data==="Error 1"){
        $("#status").text("USER NOT FOUND!");
        $("input[name=uid]").val("");
        $("input[name=pwd]").val("");
    }
    else if(data==="Error 2"){
        $("#status").text("INCORRECT PASSWORD!");
        $("input[name=pwd]").val("");
    }
    else{
        window.location='page2.php';
    }
}

do_login.php

<?php
    session_start();
    $uid=$_POST['UID'];
    $pass=$_POST['PASS'];

    $connection = mysqli_connect("localhost","shreyansh","","ajax");
    $query1 = "SELECT user FROM login WHERE user = '$uid' AND pass = '$pass' ";
    $query2 = "SELECT user FROM login WHERE user = '$uid'";
    $result = mysqli_fetch_array(mysqli_query($connection,$query1));
    // checking credentials
    $response = "";
    if(count($result)==0){
        $res = mysqli_fetch_array(mysqli_query($connection,$query2));
        if(count($res)==0){
            $response = "Error 1";
        }
        else
            $response = "Error 2";
    }
    else{
        $_SESSION['username']=$uid;
    }
    echo $response;
?>

page2.php

<?php
    session_start();
    if(!isset($_SESSION['username']) || empty($_SESSION['username']))
    header("Location: login.php");
?>
<!DOCTYPE html>
<head>
    <title>Welcome Page</title>
    <script type="text/javascript" src="login.js"></script>
</head>
<body>
    <p>Hello <?php echo $_SESSION['username']?> </p>
</body>

The main objective is to show error messages in the login.php page and redirect to page2.php if the credentials are correct.
On pressing the login button the page gets redirected to page2.php but nothing is displayed. The entire webpage is blank. Please identify the error in my code.

shreyansh
  • 97
  • 8

3 Answers3

2

You have a typo in code:

<?php
    session_start();
    if(!isset($_SESSION(['username'])) || empty($_SESSION['username']))
    header("Location: login.php");
?>

$_SESSION is not a function so using it with () will return an error. Also just a header does not prevent the page from running, so your code will still be executed. You have to prevent the code execution after setting the location header

<?php
    session_start();
    if(!isset($_SESSION['username']) || empty($_SESSION['username'])) {
        header("Location: login.php");
        die();
    }
?>

You also have a mysql injection in your sql "SELECT user FROM login WHERE user = '$uid'" https://en.wikipedia.org/wiki/SQL_injection

Try using ' or 1 or 'a as the username

The easiest way to prevent it is to enclosure the variables passed to your query with addslashes:

"SELECT user FROM login WHERE user = '" . addslashes($uid) . "'"
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dimitri L.
  • 4,499
  • 1
  • 15
  • 19
1

first of all, I strongly recommand that you consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection

Also, you should not store plain-text password, therefore:

you should really consider using password_hash and his fellow collegue password_verify

Beside that, I would make your code a little different, such as :

-> modify generateResponse function as this:

function generateResponse(data,uid){
if(data === "Error"){
    $("#status").text("user not found : make sure you are using correct credentials.");
    $("input[name=uid]").val("");
    $("input[name=pwd]").val("");
}
else {
    window.location='page2.php';
}
}

-> use only one query (that's where PPS will be more safe)

<?php
session_start();

$connection = mysqli_connect("localhost","shreyansh","","ajax");
$query1 = "SELECT user FROM login WHERE user = '$uid' AND pass = '$pass' ";
$result = mysqli_fetch_array(mysqli_query($connection,$query1));
// checking credentials
$response = "";
if(count($result) == 0){ $response = "Error"; } else { $_SESSION['username'] = $uid; $response = ""; }
echo $response;

?>

-> finally, correct the misuse of $_SESSION in page2.php (CREDIT goes to @Dimitri-L)

<?php
session_start();
if(!isset($_SESSION['username']) || empty($_SESSION['username']))
{
header("Location: login.php");
}
else
{
?>
<p>Hello <?php echo $_SESSION['username']; ?></p>
<?php
}
?>
Community
  • 1
  • 1
OldPadawan
  • 1,247
  • 3
  • 16
  • 25
0

config.php

session_start();

DB credentials // you can also write your DB details here

do_login.php

include_once('config.php');

your code for login.

page2.php

include_once('config.php');

print_r($_SESSION);

Zaid Bin Khalid
  • 748
  • 8
  • 25