Monday, 6 March 2017

Create a PHP script which returns JSON response on GET requests

Hello Guys,
In this post, we will create a PHP script which will return JSON response, when we send GET request to it. Basically, we will be developing a simple API for our requirements. Any PHP API has 3 files,

  1. config.php [The Database Configuration File]
  2. myClass.php [The Class containing functions, for modularity]
  3. index.php [The Handler, which invokes respective functions, on GET Requests]

For Detailed Information, have a look on this video



Without wasting any time, lets jump into the codes,
1. config.php
<?php
define("DB_NAME","test");
define("DB_USER","root");
define("DB_PASS","");
define("DB_HOST","localhost");
?>
2. myCLass.php
<?php
require_once 'config.php';
class myClass
{
 public function check($user,$pass)
 {
  $con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
  $res=mysqli_query($con,"select pass from users where user = '$user'");
  $pa = mysqli_fetch_array($res)[0];
  $arr = array();
  if ($pa == $pass)
   $arr=array('check' => 'True','user' => "$user");
  else
   $arr=array('check' => 'False');
  return $arr;  
 }
 public function register($user,$pass,$email)
 {
  $con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
  $res=mysqli_query($con,"insert into users values ('$user','$pass','$email')");
  if($res)
   $arr=array('check' => 'True');
  else
   $arr=array('check' => 'False');
  return $arr;  
 }
 public function show($user)
 {
  $con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
  $res=mysqli_query($con,"select * from users where user = '$user'");
  $arr = array();
  while($row = $res->fetch_assoc())
  {
   $arr[]= $row;
  }
  return $arr;
 }
}
?>
3. index.php
<?php
require_once 'myClass.php';
$db = new myClass();

if(isset($_GET["user"]) && isset($_GET["pass"]) && isset($_GET["email"]))
{
 echo json_encode($db->register($_GET["user"],$_GET["pass"],$_GET["email"]));
}
else if(isset($_GET["user"]) && isset($_GET["pass"]))
{
 echo json_encode($db->check($_GET["user"],$_GET["pass"])); 
}
else if(isset($_GET["user"]))
{
 echo json_encode($db->show($_GET["user"]));
}
else
{
 echo "API SERVER - Send Request To Get Response.";
}
?>


Hope you enjoyed reading this post, share with your friends and help us grow. Make sure you subscribe us, to get the latest from us.

0 comments:

Post a Comment