-1

I have created a login page in Reactjs and I have a login_check code in PHP. Now I have to check if the user exists in the database and if exists I want to create a token otherwise no. I used jquery to post the data when the user enters his/her details. But every time it gives a sorry message in the console don't know whether the data is getting posted to PHP or not. Here's my code.

Sigin.js

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom'
import axios from 'axios'
import $ from 'jquery'
class Signin extends Component {
constructor(props)
{
    super(props);
    const token = localStorage.getItem("token")

    let loggedIn = true
    if(token == null)
    {
        loggedIn = false
    }

    this.state = {
        email: '',
        password: '',
        loggedIn
    }

    this.onChange = this.onChange.bind(this)
    this.submitForm = this.submitForm.bind(this)
}

onChange(e){
    this.setState({
        [e.target.name] : e.target.value
    })
}


submitForm(e){
    e.preventDefault();
    // const { email, password } = this.state

    // if(email === "admin@123" && password === "admin")
    // {
    //     localStorage.setItem("token", "loggedIn")
    //     this.setState({
    //         loggedIn: true
    //     })
    //     console.log("Logged In!")
    // }
    // else
    // {
    //     alert("Invalid email or password!");
    //     console.log("Invalid email or password!")
    // }


        $.post("http://localhost/php-react-rest-api-crud/login_check.php", function(data){
                if(data === "1")
                {
                    localStorage.setItem("token", "loggedIn")
                    console.log("success!");
                }
                else if(data === "0")
                {
                    console.log("sorry!");
                }
            })

}
render() {
    if(this.state.loggedIn)
    {
        return <Redirect to = "/admin" /> 
    }
    return (

        <div>
            <h1>Login</h1>

            <form onSubmit={this.submitForm}>
                <input type="email" name="email" placeholder="Enter email" value={this.state.email} onChange={this.onChange}/>
                <input type="password" name="password" placeholder="Enter Password" value={this.state.password} onChange={this.onChange}/>
                <br />
                <input type="submit"/>
            </form>
        </div>
    );
  }
}

export default Signin;

login_check.php

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
header("Access-Control-Allow-Methods: GET, POST");

$conn = mysqli_connect("localhost", "root", "", "farmer_portal");
if(!$conn)
{
    die('Connection error'.mysqli_connect_errno());
}


if((!isset($_POST['email'])) && (!isset($_POST['password'])))
{
   echo "0"; 
   exit();
}

$myemail = $_POST['email'];
$mypassword= $_POST['password'];


$email = "SELECT * FROM signup WHERE email='$myemail' ";
$pass = "SELECT * FROM signup WHERE password='$mypassword' ";

$myemail = stripslashes($email);
$mypassword = stripslashes($password);

$res_e = mysqli_query($conn,$myemail);
$res_p = mysqli_query($conn,$mypassword);

if(mysqli_num_rows($res_p) > 0 && mysqli_num_rows($res_e) > 0)
{
echo "1";
}
else
{
  echo "0";
}

?>
  • You should use only react and call using fetch or axios and should not use jquery here. Also please add your login check code – Niraj Feb 13 '20 at 08:04
  • Hi there, I used axios before but it is not validating the details, simply it shows success for every entered details and redirects it to admin page. I have already added login_check code. – Abhishek Marubadi Feb 13 '20 at 08:19
  • debug php code problem might be there – Niraj Feb 13 '20 at 08:30
  • Go to the browser developer tools -> Network Tab; and check the request headers and Form Data. You should be able to see all the $_POST variables being sent to PHP. use this to troubleshoot. – Olamide226 Feb 13 '20 at 08:48
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Feb 13 '20 at 11:02

1 Answers1

1

A little bit about your code first, if I may

I see that you import Axios but never use it, instead using jQuery to post your ajax request. If that’s all you’re using jQuery for, I highly recommend dumping it and sticking to Axios. It’s great at what it does.

Secondly, whenever possible, avoid multiple SQL requests if you can get away with fewer or, even better, only one. These two requests:

$email = "SELECT * FROM signup WHERE email='$myemail' ";
$pass = "SELECT * FROM signup WHERE password='$mypassword' ";

Should be made into one:

$user_info = "SELECT * FROM signup WHERE email='$myemail' AND password='$mypassword'";

You should also check the contents of $myemail and $mypassword. stripslashes() isn’t nearly enough to prevent mysql injections. More on that subject here.

Never trust user input. Always check you’re getting what you’re expecting, in your case that $myemail is indeed an email and that password is indeed a string. PHP provides two functions to that end, filter_var($myemail, FILTER_VALIDATE_EMAIL) and is_string($mypassword).

Finally, and maybe the most important point: don’t store non-hashed passwords. PHP provides password_hash($mypassword) to store passwords and password_verify($mypassword) to check your user input against database.

Now to address your question

The answer lies in your JS code :

$.post("http://localhost/php-react-rest-api-crud/login_check.php", function(data) {
    // ...
});

Both in Axios and jQuery, the second parameter of the post() function should be your data, meaning user email and password. But here, you don’t send any data, you jump straight to handling the response to your AJAX request. Hence why PHP returns "0".

thizel
  • 11
  • 1
  • Hi thizel, I used Axios method it worked fine.Output is 1 if the details are correct otherwise 0. Now I want to validate if the user exists in DB. If yes it should redirect to another page. Where do I write that condition in axios? – Abhishek Marubadi Feb 13 '20 at 10:54