article

Tuesday, August 19, 2014

Creating a RESTful Web Service in PHP

Creating a RESTful Web Service in PHP
<?
// process client request via url
header("Content-Type:application/json");
if (!empty($_GET['name'])) {
 
 $name = $_GET['name'];
 $price = get_price($name);
 
 if (empty($name))
  deliver_response(200,"book not found", null);
 else
  deliver_response(200,"book found", $price);
}else{
 deliver_response(400,"Invalid request", null);
}

function deliver_response($status,$status_message,$data)
{
 header("HTTP/1.1 $status $status_message");
 $response['status'] = $status;
 $response['status_message'] = $status_message;
 $response['data']=$data;

 $json_response = json_encode($response); 
 echo $json_response;
}
function get_price($find) {
 $books=array(
  "java" =>299,
  "c" =>348,
  "php" =>267
 );

 foreach ($books as $book=>$price){
 if ($book==$find) {
  return $price;
  break;
 }
 }
}
?>
//.htaccess file
# Turn on the rewrite engin
Options +FollowSymLinks
RewriteEngine On

#request routing
RewriteRule ^([a-zA-Z]*)$ index.php?name=$1 [nc,qsa]

Related Post