1

I've got 2 files, one is the login.php and other is loginprocess.php, what I would like to happen is when I click the submit button in login.php, a SweetAlert notif will popup that it is a succesful login then redirects to another .php page and when credentials are incorrect it displays a swal error and goes back to login again.

Login Form:

enter image description here

Here's my code:

login.php

    <!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>

  <script src="sweet\node_modules\sweetalert\dist\sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="sweet\node_modules\sweetalert\dist\sweetalert.css">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"/> 

</head>
<body>
    <form action="student_logprocess.php" method="POST">
    <div class="container">
        <h2><center>Student Login Form</center></h2><hr>
         <h4><center>Please login to continue</center></h4>

         <div class="row">
   <div class="col-md-4 col-md-offset-4">
      <div class="panel panel-default">
         <div class="panel-body">
        <div class="form-group">
             <center><img src="img/user.png" class="img-circle img-thumbnail" width="200" alt="UserPhoto" />
        </center>
             </div>

<div class="form-group">
<input type="text" class="form-control input-lg" placeholder="Username" name="txtusername" id="user">
</div>

<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Password" name="txtpassword" id="pw">
</div>

<div class="checkbox">
   <label>
      <input type="checkbox"> Remember me
   </label>
</div>


<button onclick="showmsg();" type="submit" class="btn btn-primary btn-lg btn-block" id="submit">Login</button>

  </div>
      </div>
 </div> 
</form>

<script type="text/javascript">
  function showmsg()
  {

    var user = 'txtusername';
    var pw = 'txtpassword';

    var userName = document.getElementById('username').value;
    var passWord = document.getElementById('password').value;

  if((username == userName) && (pw == passWord)) {
    swal("Good job!", "Login Success!", "success");
  }
  else{
    swal("Oops...", "Invalid credentials!", "error");
  }
}
</script>

  <script src="jquery-3.1.1.js"></script>
  <script src="js/bootstrap.min.js"></script>
</body>
</html>

loginprocess.php

    <?php
require_once('student_conn.php');

$fname = $_POST['txtusername'];
$password = $_POST['txtpassword'];

$sql=$db->prepare("SELECT * FROM lgn_student WHERE fname=:txtusername AND password=:txtpass");
$sql->bindParam(':txtusername',$fname);
$sql->bindParam(':txtpass',$password);
$sql->execute();

If($row=$sql->rowCount()<>0){
session_start();
$_SESSION['account']=true;

header('location:student_main.php');
}else{
    header('location:student_login.php');
}
?>

The problem here is, I can't make it work. I've tried searching here but I don't understand the code being given.. And it won't work for me.. I'm using xampp and navicat for the databases..

lgn_student is the table for login credentials

Thank you in advance!

** EDIT (using the code by Michael S.) **

student_login.php

    <!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>

  <script src="sweet\node_modules\sweetalert\dist\sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="sweet\node_modules\sweetalert\dist\sweetalert.css">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"/> 

</head>
<body>
    <form action="student_logprocess.php" method="POST">
    <div class="container">
        <h2><center>Student Login Form</center></h2><hr>
         <h4><center>Please login to continue</center></h4>

         <div class="row">
   <div class="col-md-4 col-md-offset-4">
      <div class="panel panel-default">
         <div class="panel-body">
        <div class="form-group">
             <center><img src="img/user.png" class="img-circle img-thumbnail" width="200" alt="UserPhoto" />
        </center>
             </div>

<div class="form-group">
<input type="text" class="form-control input-lg" placeholder="Username" name="txtusername" id="user">
</div>

<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Password" name="txtpassword" id="pw">
</div>

<div class="checkbox">
   <label>
      <input type="checkbox"> Remember me
   </label>
</div>


<button type="submit" class="btn btn-primary btn-lg btn-block" id="submit">Login</button>

  </div>
      </div>
 </div> 
</form>

  <script type="text/javascript">
    $(function() {

         var username = $('#user').val(),
                password = $('#pw').val(),
                smb = $('#submit');

           smb.on('click', function(e){
              e.preventDefault();

              $.post( "/htdocs/0205_stud/student_logprocess.php", 
                    {txtusername: username, txtpassword: password},
                    function( data ) { 
                      
                      var_dump( $sql->fetch() );die()
                      if(data.state == 1) {
                         swal("Good job!", "Login Success!", "success");
                         
                         window.location.href = "student_main.php";
                      }
                      else
                         swal("Oops...", "Invalid credentials!", "error");
                    });
              });});

      </script>

  <script src="jquery-3.1.1.js"></script>
  <script src="js/bootstrap.min.js"></script>
</body>
</html>

student_logprocess.php

    <?php
require_once('student_conn.php');
session_start();  


$fname = $_POST['txtusername']; //Retrieve AJAX data

$password = $_POST['txtpassword']; //Retrieve AJAX data

$sql=$db->prepare("SELECT * FROM lgn_student WHERE fname=:txtusername AND password=:txtpass");
$sql->bindParam(':txtusername',$fname);
$sql->bindParam(':txtpass',$password);
$sql->execute();

if( $sql->fetch() ){

    $_SESSION['account']=true;
    $data['state'] = 1; 

}

else{

    $data['state'] = 0;  

}

header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
Humayun Ahmad Rajib
  • 1,502
  • 1
  • 10
  • 22
  • There is typo in code – Shahnawaz Kadari Feb 15 '18 at 00:34
  • @Smartpal is it the `function "showmsg();"`? I saw in yt entered that way hehe but I'll change it – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:38
  • move the java script section into tags. – Bobby Axe Feb 15 '18 at 00:39
  • Is this a live site? I sure hope not. – Funk Forty Niner Feb 15 '18 at 00:42
  • @BobbyAxe moved it, but still the same.. Is my java script correct? `function showmsg() { var user = 'txtusername'; var pw = 'txtpassword'; var userName = document.getElementById('username').value; var passWord = document.getElementById('password').value; if((username == userName) && (pw == passWord)) { swal("Good job!", "Login Success!", "success"); } else{ swal("Oops...", "Invalid credentials!", "error"); } }` – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:43
  • the login will be based on my lgn_student table.. let's say I have an account user 'abc' and pw '1234'.. Is it possible to link the var user to the table I created? – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:45
  • @arudowin Yeah, there are 3 typos, man you're doing wrong! Send ajax request from login.php to loginprocess.php if login success start session, Swal("success") and redirect user otherwise give swal("Failed") – Shahnawaz Kadari Feb 15 '18 at 00:45
  • @FunkFortyNiner what's a live site? :D – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:46
  • actually your java script is not correct the values your comparing are no where to be found move this discussion to chat lets see how we can help – Bobby Axe Feb 15 '18 at 00:46
  • @Smartpal that's my prob too tho.. I dunno what's ajax but I'll look up on it.. I wasn't explained well with these codes.. I was thinking of putting the swal where the header is in login.php – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:48
  • @BobbyAxe okay thanks – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:49
  • Live as in "on the Internet", an active one. – Funk Forty Niner Feb 15 '18 at 00:51
  • idk how to open the chat here lol – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:51
  • @FunkFortyNiner oh! no~ it's just a localhost server thing hehe – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 00:52
  • well to the problem; you say it doesn't work. You will need to be specific as to what it's not doing that you are expecting to work as. Does an alert popup? Does it show you an error? Are you looking at the developer console and checking for errors on the php and error handling on the query? Are you using `http://localhost` or as `file:///`? there are a lot of unknowns here. – Funk Forty Niner Feb 15 '18 at 01:02
  • @FunkFortyNiner I'm using localhost, and I was trying to have a swal success popup whenever I click the login button (attached above) with correct credentials and then it redirects to another page and a swal error when it's invalid credentials and goes back again to login.. The login credentials is based on my lgn_student table, and the user will be 'abc' and pw '1234' – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 01:15
  • and the code above is the code I'm using, but there's no popup – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 01:16
  • again; look at your developer console, there stands to have something in there as possible errors. – Funk Forty Niner Feb 15 '18 at 01:45
  • hi! can I replace my header with this? `header(echo 'swal({ title: "Logged In Successfully!", text: "Redirecting you..", timer: 1000, showConfirmButton: true confirmButtonColor: "#77dd77", confirmButtonText: "Okay", }, function(){ swal("Please Wait.", "Credentials Accepted...", "success"); window.location = "student_main.php"; });'` I replaced the `header('location:student_main.php'){` – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 13:00

1 Answers1

2

You shouldn’t / can’t just check if the username / password are right in the script code, because anybody can have access to it. You could use Ajax along with Php to do this if it fits with your logic.

  1. On clicking the button “Send” of your form, your Ajax logic would capture the action, and you could use the function to call a distant php file to check your credentials, i.e student_logprocess.php
  2. The php file returns you an answer, typically a Boolean state with a message for instance.
  3. In the return function of Ajax, handle the php response to show a sweet message and redirect to another page.

I didn’t show code here because similar question has already been answered on StackOverflow and could help you: Take a look at this thread: PHP + Ajax Login

Also, how to perform Ajax call with jQuery: http://api.jquery.com/jquery.ajax/

Hope it helps.


EDIT

I commented what I edited on your code to help you understand how it should work. I'll use jQuery and Ajax to perform an asynchronous call to your php file.

  1. Remove the showmsg() function from your button:

    <button type="submit" class="btn btn-primary btn-lg btn-block" id="submit">Login</button>

  2. Replace your script content with an Ajax call like this one below and call jQuery before your script and not after

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
        <script type="text/javascript">
    
    
        $(function() { //create a function that waits for the DOM to be ready
    
             var username = $('#user').val(),
                    password = $('#pw').val(),
                    smb = $('#submit');
    
               smb.on('click', function(e){ //Capture the submit button click
                  e.preventDefault(); //prevent the form to be sent when you click
    
                  //perform an Ajax POST. More info here : https://api.jquery.com/jquery.post/
                  $.post( "/path/to/your/student_logprocess.php", 
                        {u: username, p: password},
                        function( data ) { 
                          //In case of success, data will return what you defined in your php script. That'll allow you to trigger your swal notification
                          if(data.state == 1) {
                             swal("Good job!", "Login Success!", "success");
                             //redirect here
                             window.location.href = "http://example.com/account/";
                          }
                          else
                             swal("Oops...", "Invalid credentials!", "error");
                        });
                  });});
    
          </script>
    
  3. Edit your PHP script to reflect the AJAX call

    <?php
    
    session_start(); //Start session at the beginning of your script  
    
    
    $fname = $_POST['u']; //Retrieve AJAX data
    
    $password = $_POST['p']; //Retrieve AJAX data
    
    $sql=$db->prepare("SELECT * FROM lgn_student WHERE   fname=:txtusername AND password=:txtpass");
    $sql->bindParam(':txtusername',$fname);
    $sql->bindParam(':txtpass',$password);
    $sql->execute();
    
    if( $sql->fetch() ){ //Fetch Single Result with pdo, use php function count to see if you have found something
    
        $_SESSION['account']=true;
        $data['state'] = 1; 
    
    }
    
    else{
    
        $data['state'] = 0;  
    
    }
    
    header("Content-type: application/json; charset=utf-8"); //inform the browser we're sending JSON data
    echo json_encode($data); //echoing JSON encoded data as the response for the AJAX call
    
    ?>
    

Improvements

  1. Check your user data right before accessing the db. Even if prepared statements protect you against treats, it's a good behaviour to test what is entered by your application users, such as empty fields, etc. For instance, if $fname or $password is empty, you can return $data['state'] = 0 directly and skip the db request.

  2. It seems like you have your users' password in clear in your db, without any hash, and it's a critical security breach. To improve your code I encourage you to read about password hash in php, to store a hash into your lng_student password column instead of the password directly :

http://php.net/manual/en/faq.passwords.php

Michael S.
  • 116
  • 1
  • 8
  • Hii! Thank you for commenting! I'll check out the links you provided, thank you so much! T.T I'll come back if I manage to work it out.. – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 10:52
  • hi! can I replace my header with this? `header(echo 'swal({ title: "Logged In Successfully!", text: "Redirecting you..", timer: 1000, showConfirmButton: true confirmButtonColor: "#77dd77", confirmButtonText: "Okay", }, function(){ swal("Please Wait.", "Credentials Accepted...", "success"); window.location = "student_main.php"; });'` I replaced the `header('location:student_main.php'){` – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 12:59
  • Hello again! You can't, I invite you to read about header here (http://php.net/manual/en/function.header.php). Did you try the solution above? – Michael S. Feb 15 '18 at 13:45
  • Hi! I'm sorry for the late reply. I've just seen your code, I'll try it now! – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 14:38
  • this is the code that I retyped in the loginprocess.php `if(('txtusername' == $fname) && ('txtpassword' == $password)){ session_start(); $_SESSION['account']=true; $data['state'] = 1 ; }else{ $data['state'] = 0; } echo $data;` – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 14:58
  • I'm getting a _Notice: Array to string conversion in C:\xampp\htdocs\0205_stud\student_logprocess.php on line 31 Array_ haha. I'll check this up again tomorrow, I'm weak with logic :( I'm gonna try to read a bit. – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 15:15
  • Thank you for helping me! I'm gonna try doing it again tomorrow. – ᴘɪᴋᴀᴄʜᴜ Feb 15 '18 at 15:16
  • @arudowin in your php code, just replace what I wrote in your code and it should be ok. If Array to string conversion is still noticed, paste the line 35 in reply to let me know what it's about. You're welcome! – Michael S. Feb 15 '18 at 16:04
  • `echo $data;` is my line 31 haha, in the php code you provided, I should still remain the `$sql=$db->prepare("SELECT * FROM lgn_student WHERE fname=:txtusername AND password=:txtpassword"); $sql->bindParam(':txtusername',$fname); $sql->bindParam(':txtpassword',$password); $sql->execute();`? – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 07:17
  • Oh yes that makes sense, I forgot to JSON_encode the $data var. To be readable for your jQuery logic, you must encode your php data in JSON for instance. I'll edit my post with your question's answer above. If it's ok for you, please accept it ;) – Michael S. Feb 16 '18 at 08:19
  • Hii! thank you again! T.T I've tried it and managed to get through without errors :D Buuuuut, when I put incorrect details it gives me this _
    Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\0205_stud\student_logprocess.php on line 12
    {"state":1}_
    – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 09:56
  • and when I entered correctly, _{"state":1}_ The address bar also stays in _/student_loginprocess_ ... In the `header("Content-type: application/json; charset=utf-8");` should I change the application/json to a .json file? and again, in number 2 hehe in the ` $.post( "/path/to/your/student_logprocess.php", ` I just entered _student_loginprocess.php_ – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 09:56
  • Could you put `var_dump( $sql->fetch() );die()` right before the if and comment the result here please? (When you enter incorrect details). – Michael S. Feb 16 '18 at 10:03
  • I forgot the _session_start();_! Hahah but it still redirects me in _{"state":1}_ when it's correct and _{"state":0}_ when incorrect.. – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 10:04
  • You say that you are redirected to http://yoursite/student_logprocess.php ? – Michael S. Feb 16 '18 at 10:04
  • Oh yes it shouldn't redirect you. Did you place the jQuery script before the Ajax call? `` ? It must be right after the `` in order for the Ajax call to be executed – Michael S. Feb 16 '18 at 10:06
  • oh wait, I'm gonna try var_dump haha – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 10:06
  • Ok no problems. I edited my jQuery code, there was a typo. Please try the updated one otherwise it won't work. – Michael S. Feb 16 '18 at 10:17
  • I edited the PHP code too. Since you're looking for a single row only, you can directly test if `$result->fetch()` exists. – Michael S. Feb 16 '18 at 10:20
  • still _{"state":0}_ and _{"state":1}_, didn't expect sweetalert be this hard in php T.T If only it's possible to call the table (or database) directly xD – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 10:55
  • I tried changing `$sql->fetch()` to this `$row=$sql->rowCount()<>0`, still the same result.. In the JQuery `smb.on('click', function(e){` should I be declaring _e_ somewhere? – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 10:58
  • It has nothing to do with SweetAlert. Could you try my entire code again, I tested it and it's working correctly. To debug javascript, open your browser's console and check if there are no errors pls. Concerning php, what gave you the `var_dump( $sql->fetch() );die()` ? – Michael S. Feb 16 '18 at 11:04
  • I'm sorry I'm starting to get annoying.. T.T But the result is still the same when I click the login button.. Even with `var_dump`, I shall post my code above. And if ever it looks okay, I'll try to create another db and use the code again.. And in my browser's console in the _student_login.php_ there's an error.. _Uncaught ReferenceError: $ is not defined at student_login.php:51_ my line 51 is `$(function() {` – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 12:45
  • No problem. The error states that it doesn't recognise `$`, which is jQuery. So the Ajax script doesn't work and when you click on your login button, you are redirected to your `logprocess.php` page which is normal. The problem is from jQuery. Either the path is not correct or you load it after the Ajax script. I edited my answer to make you use a CDN instead of your local jQuery file. Be sure you load it before the Ajax call part like I did in my post above, point .2 – Michael S. Feb 16 '18 at 13:27
  • OMAYGAAAHD. IT WORKEED! Except the success swal though haha! I can't log in, it won't consider my login details xD But, the error swal worked!! Omaygahd. THANK YOU SO MUCH. T.T – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 14:07
  • Happy you resolved it! Yes, it's because of the redirection that triggers right after swal. You could either add a `setTimeout()` to differ the redirection for a few seconds or show a success message on the account page . Regarding your login details, it should work too. Post a new question about it or search StackOverflow if you don't find the solution ;) – Michael S. Feb 16 '18 at 14:26
  • 1
    Oki dokii, I'll try looking up for it! Thank you so much! TT.TT You saved me ;AAA; – ᴘɪᴋᴀᴄʜᴜ Feb 16 '18 at 14:28