Hi Guys, Today I’m going to create very simple Login & Signup Restful Webservices using PHP, without using any Framework or Library.
Using Core PHP, 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 & student Table
- Database Connectivity
- Creating Student 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/
├────── student.php – contains properties and methods for “student” database queries.
├─── Student/
├────── signup.php – file that will accept student data to be saved to the DB.
├────── login.php – file that will accept username & password and validate
Creating Database & students Table
Using PHPMyAdmin First create a database I’m using webservice as the database name. For keeping things simple we’ll create very simple students Table with very few columns.
Run this SQL Query to create a student table
CREATE TABLE `students` (
`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 = "webservice";
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 Student Class with Signup & Login methods
In your “api” folder, create a new folder “objects” and create a new file there as “student.php” and paste this code there
<?php
class Student {
// database connection and table name
private $conn;
private $table_name = "students";
// object properties
public $id;
public $username;
public $password;
public $created;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// signup student
function signup(){
}
// login student
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 student
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 “student.php” file, here is the complete code for “student.php” file
<?php
class Student{
// database connection and table name
private $conn;
private $table_name = "students";
// object properties
public $id;
public $username;
public $password;
public $created;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// signup student
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 student
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 “Student” and create a new file there as “signup.php” and paste this code there
<?php
// get database connection
include_once '../config/database.php';
// instantiate student object
include_once '../objects/student.php';
$database = new Database();
$db = $database->getConnection();
$student = new Student($db);
// set student property values
$user->username = $_POST['username'];
$user->password = $_POST['password'];
$user->created = date('Y-m-d H:i:s');
// create the student
if($student->signup()){
$student_arr=array(
"status" => true,
"message" => "Successfully Signup!",
"id" => $student->id,
"username" => $student->username
);
}
else{
$student_arr=array(
"status" => false,
"message" => "Username already exists!"
);
}
print_r(json_encode($student_arr));
?>
as you can see in the code above we are just calling the signup function from the “student.php” in the objects folder.
Following the same, create another file in the Student 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/student.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare user object
$student = new Student($db);
// set ID property of student to be edited
$student->username = isset($_GET['username']) ? $_GET['username'] : die();
$student->password = isset($_GET['password']) ? $_GET['password'] : die();
// read the details of user to be edited
$stmt = $student->login();
if($stmt->rowCount() > 0){
// get retrieved row
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// create array
$student_arr=array(
"status" => true,
"message" => "Successfully Login!",
"id" => $row['id'],
"username" => $row['username']
);
}
else{
$student_arr=array(
"status" => false,
"message" => "Invalid Username or Password!",
);
}
// make it json format
print_r(json_encode($student_arr));
?>
Almost done, now you keep this “api” folder in localhost server. I’m using WAMP so I’m going to paste the “api” folder in the www folder of WAMP.
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/user/signup.php with Post parameters of username, & password
and for login
http://localhost/api/user/login.php?username=ram&password=1234
Good luck and I hope this article can be useful. See you in the next article…
If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!