Restful Web Services in PHP Example – PHP + MySQL with Source Code
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
- File Structure
- Creating Database & users Table
- Database Connectivity
- Creating User Class with Signup & Login methods
- 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
You can also download complete code from Github.
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.
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!”}
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
I think you’re using POST Get method from your Client end.
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″
}
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
Hi sir, how to give json format input in our PHP login service API sir
already giving JSON format using this json_encode($user_arr)
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
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
thank you so much sir.. i refered that link after i done some small changes and the api work well.. again thanks sir