无法登录正确的电子邮件和名称 [英] unable to login in proper email and name

查看:86
本文介绍了无法登录正确的电子邮件和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX创建登录表单,我基本上是在PHP上工作的,我对ajax知识不多,当我在电子邮件ID和名称中输入任何值时,如果您能帮助我解决我的疑问,请它登录到页面并假设如果我输入了错误的名称和电子邮件,那么与其抛出错误消息(如无效的电子邮件)或命名(即使使用错误的电子邮件ID和名称也是如此),我可以使用此AJAX完全是全新的任何人都可以帮我解决这个问题,请帮忙

I'm creating login form using AJAX, i'm basically work on PHP i don have much knowledge on ajax, please if u people could help me with my doubts, when i enter any value in the email id and name then its getting logged in to the page and suppose if i give wrong name and email then instead of throwing the error message like invalid email or name its getting logged in even with wrong email id and name, i'm purely new to this AJAX please can any one help me out with this issue it would be really help full please

login.php

login.php

        <!DOCTYPE HTML>  
        <html>
            <head>
                <meta charset="utf-8"/>
                <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
                <script src="script.js"></script>
                <style>

                .error {
                    color: red;
                    display: none;
                }

                .div1 {
                    margin-top: -19px;
                    margin-bottom: -25px;
                    margin-left: -19px; 
                }

                .copy {
                    border-radius: 4px;
                    padding: 6px 20px;
                    border-style: ridge;
                }

                #error_message{
                    background: #F3A6A6;
                }

                .ajax_response {
                    padding: 10px 20px;
                    border: 0;
                    display: inline-block;
                    margin-top: 20px;
                    cursor: pointer;
                    display:none;
                    color:#555;
                }

                </style>
            </head>
            <body style="background-image: url(pic.jpg); background-repeat: no-repeat; background-size: cover;">  

                <div style="padding-left: 380px; padding-top:80px" class="div1">

                    <h2 style="color:#009999">Login :</h2>

                    <form action="" method="post" id="logForm" enctype="multipart/form-data">

                        <span style="color:#0099ff">Name: </span>
                        <input type="text" name="name" id="name" class="copy" style="margin-left: 52px"  value ="" />
                        <span class="namee error">Enter name</span>
                        <br/><br/>

                        <span style="color:#0099ff"> E-mail: </span>
                        <input type="text" name="email" id="email" class="copy" style="margin-left: 48px"  value ="" />
                        <span class="emaile error">Enter email</span>
                        <br/><br/>

                        <input type="button" id="submit" class="submit" name="submit" value="Login" /> 
                        <div id="error_message" class="ajax_response" style="float:left"></div>

                    </form>

                </div>

            </body>

            <script>
                $(document).ready(function(){
                    $("#submit").click(function(){
                        var error = false;
                        var form = document.getElementById('logForm');
                        var formData = new FormData(form);

                        // Loop through the form data
                        for(var p of formData){
                            // Check if the form data is empty
                            if(p[1] === ''){
                                // Show the error
                                $('.'+p[0]+'e').show();
                                error = true;
                            }
                        }

                        // Boolean to prevent AJAX from running in case of an error
                        if(error){
                            return false;
                        }

                        // AJAX Code To Submit Form.
                        $.ajax({
                            type: "POST",
                            url: "success.php",
                            data: formData,
                            processData: false,
                            contentType: false,
                            cache: false,
                            success: function(data){

                                if (data) {
                                    window.location = 'pannel.php';
                                    $('#success_message').fadeIn().html(data);
                                    setTimeout(function() {
                                        $('#success_message').fadeOut("slow");
                                    }, 2000 );
                                }

                            }

                        });

                    });

                });
            </script>

        </html> 

success.php

success.php

        <?php
                $mysqli  = mysqli_connect("localhost","root","","ajax1");
                session_start();

                if (isset($_SESSION['id'])){
                    header('location:pannel.php');
                        }

                    $email=$_POST["email"];
                    $name=$_POST["name"];

                    //Checking is user existing in the database or not
                    $query = "SELECT * FROM `users` WHERE name='$name' and email='$email'";
                    $result = mysqli_query($mysqli,$query);
                    $row1 = mysqli_fetch_array($result);
                    $rows = mysqli_num_rows($result);

                    if($rows==1){
                        $_SESSION['name'] = $name;
                        $_SESSION['id']=$row1['userid'];
                        // Redirect user to index.php
                        header("Location: pannel.php");
                        }
                         else{
                             $error = " Invalid Name or E-MAIL ";
                            }
            ?>

pannel.php

pannel.php

        <!DOCTYPE html>
        <html lang="en">
                <head>

                    <title>Bootstrap Example</title>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1">
                    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
                    <style>

                            #success_message{
                                background: #CCF5CC;
                            }

                        .ajax_response {
                            padding: 10px 20px;
                            border: 0;
                            display: inline-block;
                            margin-top: 20px;
                            cursor: pointer;
                            display:none;
                            color:#555;
                        }
                    </style>

                </head>
            <body>

                <div id="success_message" class="ajax_response" style="float:left"></div>

                <div class="container">
                    <br><br><br><br>
                    <?php

                        $mysqli  = mysqli_connect("localhost","root","","ajax1");
                        $query=mysqli_query($mysqli,"select * from `users` where userid='".$_SESSION['id']."'");
                        $row=mysqli_fetch_array($query);
                        echo 'Welcome - '.$row['name'];

                    ?>

                    <br>
                    <a href="logout.php">Logout</a>
                    <br><br>



                </div>

            </body>
        </html>                 

推荐答案

要考虑的几件事:

1.)您没有使用参数化的sql查询,因此您的数据库仍然可以进行sql注入.我更改了查询结构,以演示如何使用参数化查询.请停止这样做.这里是这个主题的链接.阅读它,将其添加为书签,然后对其进行引用,直到您了解为止.这很重要,一旦您做了几次,就不难了.

1.) You are not using parameterized sql queries thus leaving your db open to sql injection. I changed your query structure to demonstrate how to use parameterized queries. Please stop doing it the way are doing it. Here is a link on this subject. Read it, bookmark it, and refer to it until you understand it. It's that important and not hard once you do it a few times.

https://websitebeaver.com/prepared -statements-in-php-mysqli-to-prevent-sql-jection

2.)当您使用ajax时,这就是发生的情况.您的主要html页面正在向另一个页面发送ajax查询.该页面接收响应,执行任何代码,然后将答案发送回发送请求的主html页面的ajax函数.

2.) When you use ajax here is what it happening. Your main html page is sending out an ajax query to another page. That page receives the response, does whatever code, and then sends an answer back to the main html page's ajax function that sent the request.

该响应在ajax函数的成功块中接收.我认为,来回传递数据的最简单方法是使用JSON格式.

That response is received in the success block of the ajax function. The easiest way to pass data back and forth in my opinion is using the JSON format.

3.)php中回显的任何内容都将发送到ajax函数.

3.) Anything echoed in php will be sent to the ajax function.

4.)在我的示例中,数据是json字符串,而不是json对象,因此您必须将字符串转换为json对象.

4.)The data in my example is a json string not a json object so you have to convert the string to a json object.

5.)在构建新代码时,请分小块进行,直到您所从事的工作达到您的期望为止.然后修饰工作代码以执行所需的操作.这样可以节省您进行故障排除的时间,并帮助您在花费大量时间编码可能发生的事情之前,找出代码的最佳工作流程.

5.)When building new code, do it in small blocks and do not move on until whatever you are working on works how you would expect. Then embellish the working code to do what you want. This will save you hours in troubleshooting and help you figure out the best workflow of your code before you spend hours coding what you think is going to happen.

6.)您可以使用名称和电子邮件来验证登录名,但是名称是通用的,人们可以共享电子邮件.我会做类似电子邮件/用户名和密码的操作.对于密码,请使用php的本机密码功能.

6.) You can use name and emails for validating a login, but names are common and people can share emails. I would do something like an email/username and a password. For passwords use the php's native password functions.

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

因此,这是一个示例,可以使您走上正轨.

So here is an example that should get you on the right track.

在您的login.php上,将ajax函数更改为此:

On your login.php change your ajax function to this:

$.ajax({
  type: "POST",
  url: "success.php",
  data: formData,
  processData: false,
  contentType: false,
  cache: false,
  dataType: 'application/json; charset=utf-8',
  success: function(response){
    console.log('Ajax tried.');
    console.log(response);
    var data = JSON.parse(response); //Change from string to object.
    console.log(data);
    if (data['success']) {
        console.log('It worked!!!!');
        //The user's name and email returned a 
        //result from the user's table. 

    } else{
      console.log('You have an error.');
      console.log(data['errors']);
      //Here are your errors.  Do something with them.
    }

  }

});

将您的success.php更改为此:

Change your success.php to this:

<?php

session_start(); //Always do first.

$mysqli  = mysqli_connect("localhost","root","","ajax1");

if (isset($_SESSION['id'])){ //<--This should not be here.  This should
//be tested for on the login.php page.
$errors['logged_in'] = TRUE;  

}

//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE name=? and email=?";  //<--Use placeholders.

//Remember this:  Prepare, bind, Execute.



$stmt = $mysqli->prepare($query); //Prepare
$stmt->bind_param("ss", $_POST['name'], $_POST['email']); //Bind
$stmt->execute(); //Execute.
$result = $stmt->get_result()->fetch_assoc();

if($result){

  $_SESSION['name'] = $result['name']; //Safer to use data from db instead of post.
  $_SESSION['id']   = $result['userid'];

}else{

  $errors['user_exists'] = FALSE;

  }

$stmt->close(); //Important to free up resources for your next query.

$response = array();

if(isset($errors) && $errors){

  $response['success'] = FALSE;
  $response['errors'] = $errors;

} else{

  $response['success'] = TRUE;


  }

echo json_encode($response); //<-- This is what gets sent back to ajax function.

?>

希望这会有所帮助:)

这篇关于无法登录正确的电子邮件和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆