PHP MySQLi Login API

Jyotishgher Astrology
By -
0

 PHP MySQL Login Json API For Website and Mobile Apps.

In this PHP MySQLi Login API , we will learn how to create a PHP MySQL Login Api with the help of PHP and MySQL database. There are few steps given for creating a login Api with MySQL database which we can use directly in Mobile apps or website.

PHP MySQLi Login API



Environment Setup

Now, we need to start the webserver and create the files for the login system. There are few steps that are given below to setup the environment.

  • Open the XAMPP or wamp Control Panel.
  • Start the Apache server by clicking on the Start button.
  • Start the MySQL by clicking on the Start button.
  • Create all the files needed for login.
  • Create login table in the database using phpMyAdmin in XAMPP  or wamp.

To create a PHP and MySQL-based login JSON API that can be used for both websites and mobile apps, follow these steps:

1. Set Up MySQL Database

First, create a MySQL database and a users table.

CREATE DATABASE user_auth;


USE user_auth;


CREATE TABLE users (

    id INT AUTO_INCREMENT PRIMARY KEY,

    username VARCHAR(50) NOT NULL UNIQUE,

    password VARCHAR(255) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);


PHP SCRIPT EXAMPLE:

2. PHP Backend for Login API

Create a PHP file (login.php) to handle the login requests.

login.php

<?php
header('Content-Type: application/json');

$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "user_auth";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die(json_encode(["status" => "error", "message" => "Connection failed: " . $conn->connect_error]));
}

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['username']) || !isset($data['password'])) {
    echo json_encode(["status" => "error", "message" => "Missing required fields"]);
    exit;
}

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

$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user && password_verify($password, $user['password'])) {
    echo json_encode(["status" => "success", "message" => "Login successful", "user" => $user]);
} else {
    echo json_encode(["status" => "error", "message" => "Invalid username or password"]);
}

$conn->close();
?>

4. Using the API

You can use these endpoints with any HTTP client. Here's an example using JavaScript (fetch API):


fetch('https://yourdomain.com/login.php', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json'

    },

    body: JSON.stringify({

        username: 'your_username',

        password: 'your_password'

    })

})

.then(response => response.json())

.then(data => {

    if (data.status === 'success') {

        console.log('Login successful', data.user);

    } else {

        console.error('Login failed', data.message);

    }

})

.catch(error => console.error('Error:', error));


Summary

  • Set up your MySQL database and users table for PHP MySQLi Login API .
  • Create login.php to handle login requests.
  • Optionally, create register.php for user registration.
  • Use the API with HTTP requests from your website or mobile app.
Tags:

Post a Comment

0Comments

Post a Comment (0)