Topic: Basic PHP REST example
For anyone struggling with a PHP implementation of REST here is something very crude, but seemingly working(?), that I've thrown together. It uses the HTTP_Request2 PEAR package which will need installing if you don't already have it. (Probably just a few clicks on your ISP's control panel, though I had to fiddle with the include path afterwards to get it included).
I had to override the certificate check which fails otherwise. No idea why, and well beyond my capabilitiies to understand such things! Maybe someone can advise on this.
Better implementations/suggestions welcome pleased. With the current dearth of PHP-based examples I'm just sticking my head over the parapet in the hope that having a target will draw the fire of better solutions, including industrial-grade coding...
(I'm abandoning pure JavaScript attempts as this will expose username and password required to get data(?)).
<?php
//===============
// Uses the PEAR HTTP_Request2 package
// This bit includes the necessary code. Your PHP include path may need fiddling with...
//===============
require_once "PEAR.php";
require_once "HTTP/Request2.php";
$verify = 0; // Gateway currently failing certificate test(?!). Setting this to zero ignores this.
//===============
// Login
//===============
$cmnd = 'https://data.nbn.org.uk/api/user/login';
$args = array('username' => 'XXXXXXXX',
'password' => 'XXXXXXXX'
);
$request = new HTTP_Request2($cmnd, HTTP_Request2::METHOD_GET, array('use_brackets' => true));
$request->setConfig('ssl_verify_peer', $verify);
$url = $request->getUrl();
$url->setQueryVariables($args);
$response = $request->send();
//echo $response->getBody();
$nbn_cookie = "";
foreach ($response->getCookies() as $c)
{
if ($c['name'] == 'nbn.token_key')
{
$nbn_cookie = $c['value'];
//echo "Found NBN Cookie = " . $nbn_cookie . "<br/>";
}
}
if ($nbn_cookie == "") { exit("NBN cookie not found! Aborting further execution."); }
//===============
// Example Request (using 'GET'). Gets Clouded Yellow records in TL01E
//===============
$cmnd = 'https://data.nbn.org.uk/api/taxonObservations';
$args = array('ptvk' => 'NHMSYS0000501953',
'gridRef' => 'TL01E'
);
$request = new HTTP_Request2($cmnd, HTTP_Request2::METHOD_GET, array('use_brackets' => true));
$request->addCookie('nbn.token_key', $nbn_cookie);
$request->setConfig('ssl_verify_peer', $verify);
$url = $request->getUrl();
$url->setQueryVariables($args);
$response = $request->send();
echo $response->getBody();
//===============
// Logout
//===============
$cmnd = 'https://data.nbn.org.uk/api/user/logout';
$request = new HTTP_Request2($cmnd, HTTP_Request2::METHOD_GET, array('use_brackets' => true));
$request->addCookie('nbn.token_key', $nbn_cookie);
$request->setConfig('ssl_verify_peer', $verify);
$url = $request->getUrl();
$response = $request->send();
//echo $response->getBody();
?>
Regards, Keith