login api using php

In this article, we will discuss about web service or Rest API and create a simple login web service or Rest API using PHP, Mysql, and JSON.

What is web service or Rest API ?

A web service is a way of communication between a client-server application or application component for communication. Web service is any piece of software or application that provides standardized web protocols (HTTP or HTTPS) to interoperate, communicate, and exchange data messaging. API and Web service serve as a means of communication.

Example –

Create a Database –

First of all, create a database and named it as Test, after this, we create a Table named as user having six Columns.

In our last tutorial, we have discussed about How to create a Registration web service / Rest API using Php, Mysql, and JSON.

Connecting Php with Mysql Database –

Create a file named Config.php and use it to write the configuration details of the database.



Inside Config.php file the database user name is root and the password is also root, and the database name is Test.

Now we create a file named Con.php to create a connection with the database.


require_once 'config.php';
class Connection{
   private $connect;
   function __construct(){
   $this->connect=mysqli_connect(hostname,user,password,db_name) or die("DB Connection error.");
   public function get_connection()
       return $this->connect;

After this, we are going create another file named login.php, where we will handle all the API calls.

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

class User
private $db;
private $connection;
function __construct()
$this->db = new DB_Connection();
public function does_user_exist($mail,$pass){
$query = "SELECT * FROM user WHERE email='$mail' AND password='$pass'";
$row= mysqli_fetch_array($result);
$data = array(); 
array_push($data,array( "user_id"=>$row['user_id'],
"password"=>$row['password'], ) );

$json['message']='Login Successful';

echo json_encode($json);

}else { 
$json['message']='Wrong email or password';
echo json_encode($json);

$user = new User();
if (!empty($mail) && !empty($pass)) {
$user-> does_user_exist($mail,$encrypted_password);
}else {
$json['message']='You must fill both fields';
echo json_encode($json);

Now we can test it using Postman with the given key name email, and password.

%d bloggers like this: