A Crave to Make an Impact-‎ > ‎Tools - Business‎ > ‎Web Service‎ > ‎ReST‎ > ‎

ReST in PHP

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.

By Dr. M. Elkstein
Comments