I am learning to write a Restful webservice in PHP. So I followed a video tutorial and wrote the following basic webservice. The problem is that when I tried to access the web service via http://localhost/Test8/?name=c
(because my index.php
is located in Test8
directory) URL, I get a blank page .
But when the tutor in the video accessed it using http://localhost/rest/?name=c
(because their index.php
located in rest
directory), they got {"status":200, "status_message":"Book found", "data":348}
in the webpage.
What did I miss?
index.php:
<?php
//Process client's request (via URL)
header("Content-Type:application/json");
if ( !empty($GET['name']) ) {
$name = $GET['name'];
$price = get_price($name);
if (empty($price)) {
//Book not found
deliver_response(200, 'Book not found!', NULL);
} else {
//Send the response with book price
deliver_response(200, 'Book found', $price);
}
} else {
//throw invalid request
deliver_response(400, "Invalid Request", NULL);
}
//API Functions
function get_price($bookRequested) {
$books = array(
'Java' => 999,
'C' => 348,
'PHP' =>500
);
foreach ($books as $book=>$price) {
if ($book == $bookRequested) {
return $price;
}
}
}
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);
}
?>
EDIT:
Just checked the console. It says Failed to load resource: the server responded with a status of 400 (Invalid Request)
...
I changed
if ( !empty($GET['name']) ) {
...
} else {
//throw invalid request
...
}
to
if ( !empty($GET['name']) ) {
echo '$GET["name"] is NOT empty';
...
} else {
echo '$GET["name"] IS empty';
//throw invalid request
...
}
and the browser prints $GET["name"] IS empty
.
your deliver_response()
function doesn't actually send the result to the browser. It just encodes the $response
as JSON and stores it in $json_response
.
Try adding an echo $json_response;
to the end of that function.
And then, access your URL: http://localhost/Test8/?name=Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.