Categories
PHP React

React User Login Example

Ultimately dumb example, which posts login information to php backend then backend sends result back as json.

Login.db

CREATE TABLE "users" (
	"id"	INTEGER PRIMARY KEY AUTOINCREMENT,
	"username"	TEXT,
	"password"	TEXT
)

Login.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json; charset=utf-8");

error_reporting(0);

$username= $_POST['username'];
$password= $_POST['password'];

$db = new SQLite3('login.db');
$statement = $db->prepare('SELECT count(*) FROM users WHERE username=:username AND password=:password');
$statement->bindValue(':username', $username, SQLITE3_TEXT);
$statement->bindValue(':password', $password, SQLITE3_TEXT);
$result = $statement->execute();

while ($row= $result->fetchArray()) {
    $count = $row['count(*)'];
}

if ($count>0) {
   $output->status = "success";
} 
else {
   $output->status = "fail";
}

echo json_encode($output);

App.js

import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = { username: '', password: '', isLogged: false };
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleUsernameChange(event) {
    this.setState({ username: event.target.value });
  }
  handlePasswordChange(event) {
    this.setState({ password: event.target.value });
  }

  handleSubmit(event) {
    fetch('http://127.0.0.1/login.php', {
      method: 'POST',
      mode: 'cors',
      cache: 'no-cache',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: "username=" + this.state.username + "&password=" + this.state.password,
    }).then(response => response.json()).then(data => {
      if (data.status === "success") { this.setState({ isLogged: true }); } else { this.setState({ isLogged: false }); }
    });
    event.preventDefault();
  }

  render() {
    if (this.state.isLogged) {
      return ("Logged");
    }
    else {
      return (
        <form onSubmit={this.handleSubmit}>
          <label>
            Username:
          <input type="text" value={this.state.username} onChange={this.handleUsernameChange} />
          </label>
          <label>
            Password:
          <input type="password" value={this.state.password} onChange={this.handlePasswordChange} />
          </label>
          <input type="submit" value="Submit" />
        </form>
      );
    }
  }
}