I've been working to update the LearnWith series. The series builds UI applications--right now with Angular--and multiple backends with NodeJS, or ColdFusion. I'm creating a new book that creates services in PHP.

How do you create a REST service in PHP?

I did it this way. First, add a header:

view plain print about
1header("Content-Type: application/json; charset=UTF-8");

The Content-Type header says the results will be in JSON.

Then, get the request type:

view plain print about
1$method = $_SERVER['REQUEST_METHOD'];

The $method variable will be GET, or POST, or PUT, or whatever REST protocol you're using.

Then, use a switch statement to determine the type of request:

view plain print about
1switch ($method) {
2 case 'GET':
3 // access URL Variables
4 // $_GET["myvar"])
5 // data retrieval here;
6 echo(json_encode($result));
7 break;
8 case 'PUT':
9 // retrieve PUT body data
10 $data = json_decode(file_get_contents('php://input'));
11 // $data->
12 // Update data Here
13 echo(json_encode($result) );
14 break;
15 case 'POST':
16 // retrieve POST Body data
17 $data = json_decode(file_get_contents('php://input'));
18 // $data->myvar
19 // Create some data Here
20 echo(json_encode($result) );
21 break;
22 default:
23 echo("Unknown Request Type");
24 break;

That is pretty much it. For get requests, you can access URL variables directly, like this:

view plain print about

For PUT or POST requests, you'll most likely be sending a JSON object as the body of the request and you can access it like this:

view plain print about
1$data = json_decode(file_get_contents('php://input'));

I hope this helps someone. Be sure to check out my LearnWith series, where you'll be able to find information about integrating Angular and AngularJS with PHP very soon.