• Disclaimer
  • Privacy Policy
  • Terms of Service
  • Contact Us
  • About Us
  • Ask a Question
  • Top Back-End Frameworks Poll
  • Facebook
  • Twitter
  • RSS
  • YouTube
Coding Infinite
  • Android
  • Java
  • .Net Core
  • PHP
  • Forum
  • Top Languages Poll
  • Search for:

Restful Web Services in PHP Example – PHP + MySQL with Source Code

May 24, 2018

Hi Guys, Today I’m going to create very simple Login & Signup Restful Webservices using PHP, without using any Framework or Library.

Using PHP Core, there are many straightforward ways to directly write Webservices in a single File or each Webservice in a single File but keep in mind that code organization is one of the most important programming practice. That is the reason that developers prefer using Frameworks because frameworks provide a pre-organized project structure, but for small Applications or writing Restful Webservices, I always prefer Core PHP.

What we’ll cover in Restful Web Services in PHP Example

  1. File Structure
  2. Creating Database & users Table
  3. Database Connectivity
  4. Creating User Class with Signup & Login methods
  5. Creating SignUp & Login Restful Webservices

File Structure

We’ll use this folders & files structure for writing our Webservices.

api
├─── config/
├────── database.php – file used for connecting to the database.
├─── objects/
├────── user.php – contains properties and methods for “user” database queries.
├─── User/
├────── signup.php – file that will accept user data to be saved to the DB.
├────── login.php – file that will accept username & password and validate

Creating Database & Users Table

Using PHPMyAdmin First create a database I’m using PHPLearning as the database name. For keeping things simple we’ll create very simple users Table with very few columns.

Run this SQL Query to create a users table

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Database Connectivity

In your “api” folder, create a new folder “config” and create a new file there as “database.php” and paste this code there

<?php
class Database{
 
    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "PHPLearning";
    private $username = "root";
    private $password = "";
    public $conn;
 
    // get the database connection
    public function getConnection(){
 
        $this->conn = null;
 
        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
 
        return $this->conn;
    }
}
?>

Creating User Class with Signup & Login methods

In your “api” folder, create a new folder “objects” and create a new file there as “user.php” and paste this code there

<?php
class User{
 
    // database connection and table name
    private $conn;
    private $table_name = "users";
 
    // object properties
    public $id;
    public $username;
    public $password;
    public $created;
 
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    // signup user
    function signup(){
    
    }

    // login user
    function login(){

    }
    
    // a function to check if username already exists
    function isAlreadyExist(){

    }
}

as you can see we have empty functions for Signup & Login.

Here is the signup Function Code

// signup user
function signup(){

    if($this->isAlreadyExist()){
        return false;
    }

    // query to insert record
    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                username=:username, password=:password, created=:created";

    // prepare query
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->username=htmlspecialchars(strip_tags($this->username));
    $this->password=htmlspecialchars(strip_tags($this->password));
    $this->created=htmlspecialchars(strip_tags($this->created));

    // bind values
    $stmt->bindParam(":username", $this->username);
    $stmt->bindParam(":password", $this->password);
    $stmt->bindParam(":created", $this->created);

    // execute query
    if($stmt->execute()){
        $this->id = $this->conn->lastInsertId();
        return true;
    }

    return false;
    
}

you can see that signup function is calling isAlreadyExist function for validating if the username already exists. and here’s the code for it

function isAlreadyExist(){

    $query = "SELECT *
        FROM
            " . $this->table_name . " 
        WHERE
            username='".$this->username."'";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // execute query
    $stmt->execute();

    if($stmt->rowCount() > 0){
        return true;
    }
    else{
        return false;
    }
}

and this is the login Function Code

function login(){
    // select all query
    $query = "SELECT
                `id`, `username`, `password`, `created`
            FROM
                " . $this->table_name . " 
            WHERE
                username='".$this->username."' AND password='".$this->password."'";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // execute query
    $stmt->execute();
    return $stmt;
}

after adding functions code into “user.php” file, here is the complete code for “user.php” file

<?php
class User{
 
    // database connection and table name
    private $conn;
    private $table_name = "users";
 
    // object properties
    public $id;
    public $username;
    public $password;
    public $created;
 
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    // signup user
    function signup(){
    
        if($this->isAlreadyExist()){
            return false;
        }

        // query to insert record
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                    username=:username, password=:password, created=:created";
    
        // prepare query
        $stmt = $this->conn->prepare($query);
    
        // sanitize
        $this->username=htmlspecialchars(strip_tags($this->username));
        $this->password=htmlspecialchars(strip_tags($this->password));
        $this->created=htmlspecialchars(strip_tags($this->created));
    
        // bind values
        $stmt->bindParam(":username", $this->username);
        $stmt->bindParam(":password", $this->password);
        $stmt->bindParam(":created", $this->created);
    
        // execute query
        if($stmt->execute()){
            $this->id = $this->conn->lastInsertId();
            return true;
        }
    
        return false;
        
    }

    // login user
    function login(){
        // select all query
        $query = "SELECT
                    `id`, `username`, `password`, `created`
                FROM
                    " . $this->table_name . " 
                WHERE
                    username='".$this->username."' AND password='".$this->password."'";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();
        return $stmt;
    }

    function isAlreadyExist(){

        $query = "SELECT *
            FROM
                " . $this->table_name . " 
            WHERE
                username='".$this->username."'";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();

        if($stmt->rowCount() > 0){
            return true;
        }
        else{
            return false;
        }
    }
}

Creating SignUp & Login Webservices

In your “api” folder, create a new folder “User” and create a new file there as “signup.php” and paste this code there

<?php
 
// get database connection
include_once '../config/database.php';
 
// instantiate user object
include_once '../objects/user.php';
 
$database = new Database();
$db = $database->getConnection();
 
$user = new User($db);
 
// set user property values
$user->username = $_POST['username'];
$user->password = $_POST['password'];
$user->created = date('Y-m-d H:i:s');
 
// create the user
if($user->signup()){
    $user_arr=array(
        "status" => true,
        "message" => "Successfully Signup!",
        "id" => $user->id,
        "username" => $user->username
    );
}
else{
    $user_arr=array(
        "status" => false,
        "message" => "Username already exists!"
    );
}
print_r(json_encode($user_arr));
?>

as you can see in the code above we are just calling the signup function from the “users.php” in the objects folder.

Following the same, create another file in the User folder, name the file as “login.php” and add the code below in the file

<?php

// include database and object files
include_once '../config/database.php';
include_once '../objects/user.php';
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// prepare user object
$user = new User($db);

// set ID property of user to be edited
$user->username = isset($_GET['username']) ? $_GET['username'] : die();
$user->password = isset($_GET['password']) ? $_GET['password'] : die();

// read the details of user to be edited
$stmt = $user->login();

if($stmt->rowCount() > 0){

    // get retrieved row
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    // create array
    $user_arr=array(
        "status" => true,
        "message" => "Successfully Login!",
        "id" => $row['id'],
        "username" => $row['username']
    );
}
else{
    $user_arr=array(
        "status" => false,
        "message" => "Invalid Username or Password!",
    );
}

// make it json format
print_r(json_encode($user_arr));
?>

almost done, now you keep this “api” folder in localhost server. I’m using XAMPP so I’m going to paste the “api” folder in the htdocs folder of XAMPP.

Remember that Signup API accepting POST parameters and Login API accepting GET.

Now you can test your Signup API using this URL => http://localhost/api/users/signup.php with Post parameters of username, & password

and for login

http://localhost/api/users/login.php?username=shehryar&password=12345

You can also download complete code from Github.

Download Complete Code

Note: For keeping things simple for Beginners I’m storing the plain password in Database which is not a good practice. Password must be hashed using PHP hashing methods.

Also, See This =>  Signup Login page in PHP with Database MySQL Source Code

You might be Interested in:

Here are some more Tutorials for creating Web Application & CRUD Operations using PHP & MySQL.

  • Getting Started with Web Application using PHP & MySQL | Tutorials
  • CRUD Operations using PHP & MySQL | Tutorials with Source Code
  • Learn Object Oriented Programming In Php
  • OPP In PHP – Inheritance | Encapsulation | Abstraction | Polymorphism
Author Shehryar Khan

I'm passionate about learning new technologies as well as mentoring and helping others get started with their programming career. This blog is my way of giving back to the Community.

  • Website

Related Posts

php popularity

Reasons For The Popularity Of PHP Scripting Language

November 29, 2019
laravel 6 crud app

CRUD Operations in Laravel 6 Tutorial with Example

November 2, 2019
Laravel 6 Stripe Payment

Laravel 6 Stripe Payment Integration Tutorial

October 22, 2019

12 Comments

  1. satti 3 years ago

    after running signup page it gives me the following reply

    Notice: Undefined index: username in D:\XAMP\htdocs\LOGIN\api\User\signup.php on line 15

    Notice: Undefined index: password in D:\XAMP\htdocs\LOGIN\api\User\signup.php on line 16
    {“status”:false,”message”:”Username already exists!”}

  2. manoj kumar 3 years ago

    when i am tring to insert record bu ysing signup.php null record means no insert
    // set user property values
    $user->username = $_POST[‘username’];
    $user->password = $_POST[‘password’];

    but when i use

    $user->username = $_GET[‘username’];
    $user->password = $_GET[‘password’];

    INSERT sucessfully. why i am using php 7.1

    • Shehryar Khan Post Author 3 years ago

      I think you’re using POST Get method from your Client end.

  3. Javier Balsas 3 years ago

    I have an alternative to login:
    login.php:
    ####################################################
    getConnection();

    // prepare user object
    $user = new User($db);

    // set ID property of user to be edited

    $data = json_decode(file_get_contents(“php://input”));
    $user->username = $data->username;//$contacto->encrypt_decrypt(‘encrypt’, $data->username);
    $user->password = $data->password;//$contacto->encrypt_decrypt(‘encrypt’, $data->password);

    // $user->username = isset($_GET[‘username’]) ? $_GET[‘username’] : die();
    // $user->password = isset($_GET[‘password’]) ? $_GET[‘password’] : die();
    // $user->username = $contacto->encrypt_decrypt(‘encrypt’, isset($_GET[‘username’]) ? $_GET[‘username’] : die());
    // $user->password = $contacto->encrypt_decrypt(‘encrypt’, isset($_GET[‘password’]) ? $_GET[‘password’] : die());

    // read the details of user to be edited

    if($user->login()){
    // get retrieved row
    http_response_code(201);

    // create array
    $user_arr=array(
    “status” => true,
    “message” => “Successfully Login!”,
    “id” =>$user->id ,
    “username” =>$user->username//$contacto->encrypt_decrypt(‘decrypt’,$user->username)
    );
    }
    else{
    http_response_code(503);
    $user_arr=array(
    “status” => false,
    “message” => “Invalid Username or Password!”,
    );
    }
    // make it json format
    echo json_encode($user_arr);
    ?>
    ##########################################################

    user.php:
    ##########################################################
    function login(){
    // select all query
    $query = “SELECT
    `id`, `username`, `password`, `created`
    FROM
    ” . $this->table_name . ”
    WHERE
    username='”.$this->username.”‘ AND password='”.$this->password.”‘”;
    // prepare query statement
    $stmt = $this->conn->prepare($query);
    // execute query
    $stmt->execute();
    if ($stmt->execute()) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $this->id = $row[‘id’];
    $this->username = $row[‘username’];
    $this->password = $row[‘password’];
    return true;
    }

    return false;

    }
    ############################################################
    postman or restler client
    {
    “username”:”johndue”,
    “password”:”12345″
    }

  4. vinayak 3 years ago

    thanks a lot sir,
    Sir i want to make android login and signup form can u please tell me how to connect this with my android project

  5. Thamizh 3 years ago

    Hi sir, how to give json format input in our PHP login service API sir

    • Shehryar Khan Post Author 3 years ago

      already giving JSON format using this json_encode($user_arr)

      • thamizh 3 years ago

        thanks sir. i am using postman rest client so i am trying to send the data from json format( body -> raw).
        {
        “username”:”shehryar”,
        “password”:”12345″
        }
        i did’t get the response.
        but i am passing the value from url is working sell
        http://localhost/REST/apii/user/login.php?username=shehryar&password=12345

        login and register like same .. please give the good solution.

        thanks in advance

        • Shehryar Khan Post Author 3 years ago

          to receive data as JSON, there is a different way.
          this link might give you an idea.
          https://stackoverflow.com/questions/18866571/receive-json-post-with-php

          • tamil 3 years ago

            thank you so much sir.. i refered that link after i done some small changes and the api work well.. again thanks sir

Next
  • Subscribe

    Subscribe to our Newsletters to get an email on every new article!

    * indicates required
  • Top Articles
    • login signup page with php mysql api
      Signup Login page in PHP with Database MySQL Source Code
      May 27, 2018
    • Programming Languages
      Here Are The Ten Best Programming Languages to learn in 2019
      December 22, 2018
    • asp.net core crud
      CRUD Operations in Asp.net Core MVC
      November 10, 2018
    • Location Tracking App Part 1
      Car Location Tracking Android App With Firebase Tutorial
      August 28, 2018
    • Bulk SMS Sender Open Source Android App
      Open Source Bulk SMS Sender Android App
      April 16, 2018
    • login page asp.net core
      Login page in Asp.net Core MVC with Database
      October 31, 2018
    • php mysql crud operations
      CRUD Operations Web App using PHP & MySQL | Part 2
      March 12, 2019
  • Facebook
  • Twitter
  • YouTube

© 2020 CODING INFINITE - ALL RIGHTS RESERVED

Top
  • Android
  • Java
  • .Net Core
  • PHP
  • Forum
  • Top Languages Poll

Type above and press Enter to search. Press Esc to cancel.