<?php
//This script will output json data
header("Content-Type:application/json");
include('BookInformation.php');
//Process client request via URL
if(!empty($_GET['name'])){
$name = $_GET['name'];
$price = getPrice($name);
if(empty($price)){
//print book not found
deliverResponse(200, "book not found", NULL);
}else{
//print book price
deliverResponse(200, "book found", $price);
}
}
else{
//print invalid request
deliverResponse(400, "Invalid Request", NULL);
}
//Create deliver response
function deliverResponse($status, $statusMessage, $data){
//header() is used to send a raw HTTP header
header("HTTP/1.1 $status $statusMessage");
//storing response in to array
$response['status'] = $status;
$response['status_message'] = $statusMessage;
$response['data'] = $data;
//converting response in to json
$jsonResponse = json_encode($response);
//printing response json data
echo ($jsonResponse);
}
<?php
//This function will return book price, given book name
function getPrice($find){
//variable storing book prices
$books = [
"java"=>288,
"c"=>786,
"php"=>237
];
foreach($books as $book => $price){
if($book === $find){
return $price;
break;
}
}
}
#Turn on rewrite engine
Options +FollowSymlinks
RewriteEngine on
#Request Routing
RewriteRule ^([a-zA-Z_-]*)$ index.php?name=$1 [nc,qsa]