ᴘɪᴋᴀᴄʜᴜ
ᴘɪᴋᴀᴄʜᴜ

Reputation: 25

Sweet Alert in PHP

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);

Upvotes: 1

Views: 35301

Answers (1)

Michael S.
Michael S.

Reputation: 126

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

Upvotes: 2

Related Questions