Building a RESTful API

API (Application Programming Interface) is a set of functions that allows the creation of applications that access the features or data of a service.

A RESTful API uses HTTP requests to GET, PUT, POST and DELETE data.

Authentication with Basic AUTH

Basic Auth is transferred as clear text, make sure to only allow https!

$users['admin'] = '$2y$10$VZMugyiDMwHKBgZ5QMvJyeU58Z4I1/ah5oChIVOZwcAo4xSHZosb.';

function basic_auth()
    {
        global $users;

        if( ! isset( $_SERVER['PHP_AUTH_USER'] ) ||
            ! array_key_exists($_SERVER['PHP_AUTH_USER'], $users) ||
            ! password_verify($_SERVER['PHP_AUTH_PW'], $users[$_SERVER['PHP_AUTH_USER']] )
            )
        {
            header('WWW-Authenticate: Basic realm="LXC API By ASBRA"');
            header('HTTP/1.0 401 Unauthorized');
            header('Content-Type: application/json; charset=UTF-8');
            echo json_encode([ 'status' => 401, 'message' => 'Unauthorized' ], JSON_PRETTY_PRINT);
            die();
        }

        return true;
    }

To be continued…