Newer
Older
<?php
/*
* SUCS PAF Lookup
* Imran Hussain - imranh@sucs.org
*
* HTTP GET request to lookup addresses when given a postcode. Created because
* the university dropped thier lookup system. And we _need_ it for our signup
* system.
*/
// If there isn't api key then die
if (isset($_GET['apikey']) == FALSE){
die("Please provide an api key");
}
// Get the api key the user is trying to use
$apikey = $_GET['apikey'];
// Import the array of api keys called $apikeys
include_once "../apikeys.php";
// If it's not valid then DIE DIE DIE
if ( in_array($apikey,$apikeys) == FALSE) {
die("Invalid api key");
}
// If they get here then they are allowed to be here
// If there isn't a postcode provided then die
if (isset($_GET['postcode']) == FALSE){
die("Please provide a postcode");
}
// Get the postcode they are trying to search for
$postcode = $_GET['postcode'];
// Openup a connection to the db, mad ident hacks
$dbconn = pg_connect("dbname=paf") or die('Could not connect: ' . pg_last_error());
// 'safely' prepare the sql statement and run it
$result = pg_query_params($dbconn, "SELECT * FROM paf WHERE postcode=$1", array($postcode)) or die('Query failed: ' . pg_last_error());
// stuff to make it throw out valid json
echo "{\"addresses\": [";
// For each result contrust an array and then json-ify it, and then spit it out
while ($row = pg_fetch_row($result)) {
// PAF is weird. Well UK addresses are weird. Not all data in PAF is useful.
// Try and stick the useful bits in an array
$address = array("postcode" => $row[0],"city" => $row[1], "road" => $row[4], "house" => $row[6], "flat" => $row[7]);
// json it, and then spit it out
echo json_encode($address).",";
}
// if you use this to get addresses you'll always get SUCS
// also horible hack to make it throw out valid json
echo json_encode(array("postcode" => "SA2 8PP","city" => "Swansea", "road" => "Swansea University", "house" => "Students Union", "flat" => "SUCS"));
// stuf to make it throw out valid json
echo "]}";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>