PHP Simple Rest Service


Make A Restful Service With PHP

This tutorial is a simple, lean-coded rest service that can be used to allow users to access specific data. Like other APIs from Flickr and other websites, you can sign up for an API that you can use on your own website. Normally, you add your username and password into a file and you are good to go.

Often, your API can accept an input and return an array of results. This tutorial will show how an authenticated user can access an array of data from your website using this rest service. It consists of three files; a client script, your server script and an .htaccess file.

Here is what is happening. When the client runs the file, it sends a curl request to the restful.php file. See the htaccess file below if you are confused why it is this file. It uses this file because the 's' in the url becomes a $_GET variable. Once curl hits the page, it checks for the $_GET string and post variables.

Then, the condition is met and the output array is delivered by via an encoded JSON variable. Since curl returns a string, encoding the data with JSON and decoding in the client script will allow you to keep the array intact. 

As you can see, the client can parse the array and do whatever he wants with it. In a real world rest service, you could query a database and return an array of results to a client based on the member's privilege.

In addition to that, the client could have a search box where they input strings of text for searching. Then, the restful.php file could create an array or an error based on the input.   

Client File

$url = 'http://example.com/foldername/s';
$curl = curl_init($url);
$curl_post_data = array(
    "username" => 1,
    "password" => 'password1',
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);

$array = json_decode(trim($curl_response), TRUE);
print_r($array);


Server File

$var = array();
$var = htmlentities($_GET['name']);
if ($var == 's') {
    if ($_POST['username'] == 10 && $_POST['password'] == 'password1') {
        $myarray = array(1, 2, 3, 4, 5, 6, $var);
        echo json_encode($myarray);
    } else {
        $myarray = array(100, 101, 102, 103, 104, $var);
        echo json_encode($myarray);
    }
} else if ($var == 'st') {
    if ($_POST['username'] == 10 && $_POST['password'] == 'password1') {
        $myarray = array(1, 2, 3, 4, 5, $var);
        echo json_encode($myarray);
    } else {
        $myarray = array(100, 101, 102, 103, $var);
        echo json_encode($myarray);
    }
}


HTACCESS File

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([a-zA-Z_-]+)$ restful.php?name=$1 [nc,qsa]
RewriteRule ^([A-Za-z_0-9]*)$ restful.php?name=$1 [nc,qsa]