javascript PHP 中的甜蜜警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48798340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sweet Alert in PHP
提问by ???????
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.
我有2个文件,一个是login.php,另一个是loginprocess.php,我想发生的是当我点击login.php中的提交按钮时,会弹出一个SweetAlert通知,说明登录成功重定向到另一个 .php 页面,当凭据不正确时,它会显示 swal 错误并再次返回登录。
Here's my code:
这是我的代码:
login.php
登录.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
<?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..
这里的问题是,我无法让它工作。我试过在这里搜索,但我不明白给出的代码..它对我不起作用..我正在使用 xampp 和 navicat 作为数据库..
lgn_student is the table for login credentials
lgn_student 是登录凭证表
Thank you in advance!
先感谢您!
** EDIT (using the code by Michael S.)**
**编辑(使用 Michael S. 的代码)**
student_login.php
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
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);
回答by Michael S.
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.
您不应该/不能只检查脚本代码中的用户名/密码是否正确,因为任何人都可以访问它。如果符合您的逻辑,您可以使用 Ajax 和 PHP 来执行此操作。
- 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
- The php file returns you an answer, typically a Boolean state with a message for instance.
- In the return function of Ajax, handle the php response to show a sweet message and redirect to another page.
- 单击表单的“发送”按钮时,您的 Ajax 逻辑将捕获该操作,您可以使用该函数调用远程 php 文件来检查您的凭据,即student_logprocess.php
- php 文件会返回一个答案,例如通常是带有消息的布尔状态。
- 在ajax的返回函数中,处理php响应显示甜蜜消息,重定向到另一个页面。
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
我没有在这里显示代码,因为 StackOverflow 上已经回答了类似的问题,可以帮助你:看看这个线程:PHP + Ajax 登录
Also, how to perform Ajax call with jQuery: http://api.jquery.com/jquery.ajax/
另外,如何使用 jQuery 执行 Ajax 调用: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.
我评论了我在您的代码中编辑的内容,以帮助您了解它应该如何工作。我将使用 jQuery 和 Ajax 对您的 php 文件执行异步调用。
Remove the showmsg() function from your button:
<button type="submit" class="btn btn-primary btn-lg btn-block" id="submit">Login</button>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>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 ?>
从按钮中删除 showmsg() 函数:
<button type="submit" class="btn btn-primary btn-lg btn-block" id="submit">Login</button>用下面这样的 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>编辑您的 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 ?>
Improvements
改进
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
$fnameor$passwordis empty, you can return$data['state'] = 0directly and skip the db request.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 :
在访问数据库之前检查您的用户数据。即使准备好的语句保护您免受对待,测试应用程序用户输入的内容也是一种很好的行为,例如空字段等。例如,如果
$fname或$password为空,您可以$data['state'] = 0直接返回并跳过数据库请求。似乎您的数据库中的用户密码很清楚,没有任何哈希值,这是一个严重的安全漏洞。为了改进您的代码,我鼓励您阅读 php 中的密码哈希,将哈希存储到 lng_student 密码列中,而不是直接存储密码:

