Last active
February 14, 2018 14:30
-
-
Save julianjupiter/5dd88491947aa6fac3e6ff410b6980f9 to your computer and use it in GitHub Desktop.
Example of PHP RESTful Web Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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