PHP中的甜蜜警报

时间:2018-02-15 00:20:18

标签: javascript php html xampp sweetalert

我有2个文件,一个是login.php,另一个是loginprocess.php,我想要发生的是当我点击login.php中的提交按钮时,会发出一个SweetAlert notif,它是一个成功登录然后重定向到另一个.php页面,当凭据不正确时,它会显示一个swal错误并再次返回登录。

Login Form

这是我的代码:

的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');
}
?>

问题在于,我无法使其发挥作用。我试过在这里搜索,但我不明白给出的代码..它对我不起作用..我正在使用xampp和navicat作为数据库..

lgn_student是登录凭据的表

提前谢谢!

** 编辑(使用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);

1 个答案:

答案 0 :(得分:0)

您不应该/不能只检查脚本代码中的用户名/密码是否正确,因为任何人都可以访问它。 如果它符合您的逻辑,您可以使用Ajax和Php来完成此操作。

  1. 单击表单上的“发送”按钮,您的Ajax逻辑将捕获该操作,您可以使用该函数调用远程php文件来检查您的凭据,即 student_logprocess.php
  2. php文件会返回一个答案,通常是一个带有例如消息的布尔状态。
  3. 在Ajax的return函数中,处理php响应以显示甜蜜消息并重定向到另一个页面。
  4. 我没有在此处显示代码,因为类似的问题已在StackOverflow上得到解答,可以帮助您: 看一下这个主题:https://maps.googleapis.com/maps/api/js?key=API_KEYv=3.22

    另外,如何使用jQuery执行Ajax调用:PHP + Ajax Login

    希望它有所帮助。

    修改

    我评论了我在您的代码上编辑的内容,以帮助您了解它应该如何工作。我将使用jQuery和Ajax对您的php文件执行异步调用。

    1. 从按钮中删除showmsg()函数:

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

    2. 使用下面的Ajax调用替换脚本内容,并在脚本之前调用jQuery,而不是在

      之后调用
          <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. 编辑PHP脚本以反映AJAX调用

      <?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
      
      ?>
      
    4. <强>改进

      1. 在访问数据库之前检查您的用户数据。即使准备好的语句可以保护您免受处理,也可以很好地测试应用程序用户输入的内容,例如空字段等。例如,如果$fname$password为空,您可以直接返回$data['state'] = 0并跳过数据库请求。

      2. 好像你有你的用户&#39;数据库中的密码清除,没有任何哈希值,这是一个严重的安全漏洞。为了改进您的代码,我建议您阅读php中的密码哈希,将哈希值存储到您的lng_student密码列而不是密码:

      3. http://api.jquery.com/jquery.ajax/