12.5. Using REST in PHP

Issuing GET Requests
Modern versions of PHP make it trivial to GET web pages: any file-access function (even include!) works seamlessly with URLs, too. Thus, you can use fopen, file_get_contents, and any other file-reading function to issue GET requests. For example:

$url = "http://www.acme.com/products/3322";
$response = file_get_contents($url);
echo $response;

Any parameters passed to GET requests must be encoded (e.g., a space is %20); you can encode strings using the urlencode function.

Issuing POST Requests
In stark contrast to the ease of doing a GET, there's no simple way to do a POST in PHP. You have to open a connection to the server and manually send all HTTP headers. Here's a simple function that will do the trick, for any HTTP method:

function httpRequest($host, $port, $method, $path, $params) {
  // Params are a map from names to values
  $paramStr = "";
  foreach ($params as $name, $val) {
    $paramStr .= $name . "=";
    $paramStr .= urlencode($val);
    $paramStr .= "&";
  }

  // Assign defaults to $method and $port, if needed
  if (empty($method)) {
    $method = 'GET';
  }
  $method = strtoupper($method);
  if (empty($port)) {
    $port = 80; // Default HTTP port
  }

  // Create the connection
  $sock = fsockopen($host, $port);
  if ($method == "GET") {
    $path .= "?" . $data;
  }
  fputs($sock, "$method $path HTTP/1.1\r\n");
  fputs($sock, "Host: $host\r\n");
  fputs($sock, "Content-type: " .
               "application/x-www-form-urlencoded\r\n");
  if ($method == "POST") {
    fputs($sock, "Content-length: " . 
                 strlen($paramStr) . "\r\n");
  }
  fputs($sock, "Connection: close\r\n\r\n");
  if ($method == "POST") {
    fputs($sock, $paramStr);
  }

  // Buffer the result
  $result = "";
  while (!feof($sock)) {
    $result .= fgets($sock,1024);
  }

  fclose($sock);
  return $result;
}

Issuing a POST request using this function is as simple as:

$resp = httpRequest("www.acme.com",
    80, "POST", "/userDetails",
    array("firstName" => "John", "lastName" => "Doe"));

One alternative to this approach is using PHP's CURL support; however, I'm not sure if it's really easier.

6 comments:

Christophe said...

Thanks for this tutorial, but what about methods PUT and DELETE in PHP?

Best Regards,
Christophe

Dr. M. Elkstein said...

Hi Christophe,

The method outlined here can also be used with "DELETE" or "PUT" as the HTTP method value ($method argument).

Ramanath said...

But I am getting an error like this:
unable to connect to http://localhost/REST/rest-server.php:80 (Unable to find the socket transport "http"
please help me
Thanks
Ramanath

Dr. M. Elkstein said...

Hi Ramanath,

It's probably a misconfiguration of PHP. Some things you could try: removing "http://" from the URL (it's the default, in some configurations); removing the ":80" from the URL (it shouldn't be where you've put it, anyway).

designreviews said...

Dear DR M.E.
I have tried the example above using cj rest service but i get a response:
You must specify a developer key:
even if i supplied it.

$url = "https://product-search.api.cj.com/v2/product-search?website-id=3429481&developerid=mykey&keywords=GPS&serviceable-area=US ";
$response = file_get_contents($url);
echo $response;

Please can you help me get over this?

Dr. M. Elkstein said...

Hello "designreviews",

It seems like the problem you're facing is specific to "cj", with which I'm not familiar. Try visiting their support forums, if they have any.