Check out our Angular Book Series.

How do I create a REST service in PHP?

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:


header("Content-Type: application/json; charset=UTF-8");

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

Then, get the request type:


$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:

switch ($method) {
case 'GET':
// access URL Variables
// $_GET["myvar"])
// data retrieval here;
echo(json_encode($result));
break;
case 'PUT':
// retrieve PUT body data
$data = json_decode(file_get_contents('php://input'));
// $data->
myvar
// Update data Here
echo(json_encode($result) );
break;
case 'POST':
// retrieve POST Body data
$data = json_decode(file_get_contents('php://input'));
// $data->myvar
// Create some data Here
echo(json_encode($result) );
break;
default:
echo("Unknown Request Type");
break;
}

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


$_GET["myvar"])

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:


$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.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.