Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Last active February 14, 2018 14:30
Show Gist options
  • Select an option

  • Save julianjupiter/5dd88491947aa6fac3e6ff410b6980f9 to your computer and use it in GitHub Desktop.

Select an option

Save julianjupiter/5dd88491947aa6fac3e6ff410b6980f9 to your computer and use it in GitHub Desktop.
Example of PHP RESTful Web Service
<?php
header("Access-Control-Allow-Origin: *");
$id = isset($_GET['id']) ? $_GET['id'] : NULL;
if ($id != NULL)
{
$contact = findById($id);
if ($contact != NULL)
{
header('Content-type: text/json');
header("HTTP/1.0 200 OK");
echo json_encode($contact);
} else {
$error = ['code' => 4, 'message' => 'Contact with ID ' . $id . ' does not exist.'];
header('Content-type: text/json');
header("HTTP/1.0 404 Not Found");
echo json_encode($error);
}
}
else
{
$contacts = findAll();
header('Content-type: text/json');
header("HTTP/1.0 200 OK");
echo json_encode($contacts);
}
function findById($id)
{
$contacts = findAll();
foreach($contacts as $contact)
{
if ($contact['id'] == $id)
{
return $contact;
}
}
return NULL;
}
function findAll()
{
return [
['id' => 1, 'lastName' => 'Rizal', 'firstName' => 'Jose', 'mobileNumber' => '09161234561'],
['id' => 2, 'lastName' => 'Bonifacio', 'firstName' => 'Andres', 'mobileNumber' => '09161234562'],
['id' => 3, 'lastName' => 'Mabini', 'firstName' => 'Apolinario', 'mobileNumber' => '09161234563']
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment