Full ExampleΒΆ
Below are the full example to demonstrate the basic structure of PHP web services.
Assume you have the following file in ./includes/User.php:
<?php
class User {
public function do_GET($params) {
$response = array(
'url' => $_SERVER['REQUEST_URI'],
);
print_r($params);
echo json_encode($response);
}
public function do_POST($params) {
$data = file_get_contents('php://input');
$data_json = json_decode($data, true);
print_r($params);
echo json_encode($data_json);
}
}
And this is index.php:
<?php
$api_credentials = array(
'user1' => 'abc123',
'user2' => 'abcxyz'
);
$resources = array(
'User',
);
include 'includes/User.php';
/***********************
Authentication
************************/
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My API"');
header('HTTP/1.1 401 Unauthorized');
exit;
} else {
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
if (!array_key_exists($username, $api_credentials)) {
header('HTTP/1.1 403 Forbidden');
exit;
}
if ($password != $api_credentials[$username]) {
header('HTTP/1.1 403 Forbidden');
exit;
}
}
/******************
Finding Resources
******************/
$paths = explode('/', $_SERVER['REQUEST_URI']);
array_shift($paths);
$resource = array_shift($paths);
if (!in_array($resource, $resources)) {
header('HTTP/1.1 404 Not Found');
exit;
}
/****************
Operations
****************/
$method = $_SERVER['REQUEST_METHOD'];
$resource_instance = new $resource;
$resource_method = 'do_' . $method;
if (method_exists($resource_instance, $resource_method)) {
call_user_func(array($resource_instance, $resource_method), $paths);
}
else {
header('HTTP/1.1 405 Method Not Allowed');
header('Allow: GET, POST');
}