Exception: Required option not passed: access_token - php

I am getting this error while trying to login with Google in Codeigniter only at first attempt
Fatal error: Uncaught exception 'Exception' with message ' in ..../application/libraries/OAuth2/Token/Access.php on line 44
Exception: Required option not passed: access_token in ..../application/libraries/OAuth2/Token/Access.php on line 44

Try to change your access.php file and change __construct method.
public function __construct(array $options = null)
{
echo "<pre>";
$new_options = array();
foreach($options as $key => $value)
{
$new_options = json_decode($key,true);
}
if ( ! isset($new_options['access_token']))
{
throw new Exception('Required option not passed: access_token'.PHP_EOL.print_r($new_options, true));
}
// if ( ! isset($options['expires_in']) and ! isset($options['expires']))
// {
// throw new Exception('We do not know when this access_token will expire');
// }
$this->access_token = $new_options['access_token'];
// Some providers (not many) give the uid here, so lets take it
isset($new_options['uid']) and $this->uid = $new_options['uid'];
//Vkontakte uses user_id instead of uid
isset($new_options['user_id']) and $this->uid = $new_options['user_id'];
//Mailru uses x_mailru_vid instead of uid
isset($new_options['x_mailru_vid']) and $this->uid = $new_options['x_mailru_vid'];
// We need to know when the token expires, add num. seconds to current time
isset($new_options['expires_in']) and $this->expires = time() + ((int) $new_options['expires_in']);
// Facebook is just being a spec ignoring jerk
isset($new_options['expires']) and $this->expires = time() + ((int) $new_options['expires']);
// Grab a refresh token so we can update access tokens when they expires
isset($new_options['refresh_token']) and $this->refresh_token = $new_options['refresh_token'];
}

If you are using oauth2, goto libraries/oauth2/provider.php there is function called access, in that switch case: POST, do it what i have shown below.
case 'POST':
$ci = get_instance();
/*$ci->load->spark('curl/1.2.1');
$ci->curl
->create($url)
->post($params, array('failonerror' => false));
$response = $ci->curl->execute();*/
Happy coding

public function __construct(array $options = null)
{
$new_options = array();
foreach($options as $key => $value)
{
$new_options = json_decode($key,true);
}
if($new_options==null || $new_options=="")
{
$new_options=$options;
}
if ( ! isset($new_options['access_token']))
{
throw new Exception('Required option not passed: access_token'.PHP_EOL.print_r($new_options, true));
}
// if ( ! isset($options['expires_in']) and ! isset($options['expires']))
// {
// throw new Exception('We do not know when this access_token will expire');
// }
$this->access_token = $new_options['access_token'];
// Some providers (not many) give the uid here, so lets take it
isset($new_options['uid']) and $this->uid = $new_options['uid'];
//Vkontakte uses user_id instead of uid
isset($new_options['user_id']) and $this->uid = $new_options['user_id'];
//Mailru uses x_mailru_vid instead of uid
isset($new_options['x_mailru_vid']) and $this->uid = $new_options['x_mailru_vid'];
// We need to know when the token expires, add num. seconds to current time
isset($new_options['expires_in']) and $this->expires = time() + ((int) $new_options['expires_in']);
// Facebook is just being a spec ignoring jerk
isset($new_options['expires']) and $this->expires = time() + ((int) $new_options['expires']);
// Grab a refresh token so we can update access tokens when they expires
isset($new_options['refresh_token']) and $this->refresh_token = $new_options['refresh_token'];
}

Related

PHP Fatal error: Uncaught Unirest\Exception: Bad URL

I'm trying to request a REST API using PHP Unirest.
The printed error is the following:
Bad URL, colon is first character
And my code:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Unirest\Request as UniRequest;
use CurlFile;
if (isset($_POST['primeiro'])) {
$where = $_POST["where"];
$equal = $_POST["equal"];
$resultado = new pedidos;
$valores = $resultado->LogIgualA($where, $equal);
}
class pedidos {
function LogIgualA($where, $equal) {
$wsURL = "localhost:8080/public";
try {
$valores = UniRequest::get($wsURL."/visual/json_log/where=".$where."/equal=".$equal, $headers, null);
} catch (Exception $e) {
echo $e->getMessage();
}
$valoresAux = $valores->body;
$valores = [];
foreach($valoresAux as $z){
$ID = $z->ID;
$DateConnection = $z->DateConnection;
$TimeToServe = $z->TimeToServe;
$ClientIP = $z->ClientIP;
$CacheCode = $z->CacheCode;
$Bytes = $z->Bytes;
$Method = $z->Method;
$RequestProtocol = $z->RequestProtocol;
$RequestIP = $z->RequestIP;
$RequestPort = $z->RequestPort;
$RequestFolder = $z->RequestFolder;
$Auth = $z->Auth;
$RouteLeft = $z->RouteLeft;
$RouteRight = $z->RouteRight;
$ContentType = $z->ContentType;
}
return $valores;
}
}
The "isset($_POST['primeiro']" is when I click the button in HTML so it calls the function in PHP.
I really don't know how to use this...
You need to prepend a protocol like https://.
There are other people having the same issue where prepending the protocol fixed this... https://github.com/Azure/doAzureParallel/issues/44
URL is not http: localhost:8080/public
Also check that there is no malicious input in your $_POST vars and maybe you need to use urlencode() on the fields containing appropriate characters.

How to get "metric" and "element" names for PHP - Adobe Analytics

I am pulling a report using the Adobe API from Omniture.
Here is the full script :
<?php
include_once('/path/SimpleRestClient.php');
// Date
$end_date = date("Y-m-d",strtotime("-1 days"));
$start_date = date("Y-m-d",strtotime("-8 days"));
// Location of the files exported
$adobe_file = '/path/Adobe_'.$end_date.'.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array
(
array('lasttouchchannel', 'product','visits','CTR(Clicks/PageViews)') // headers // ADD or DELETE metrics #
);
function GetAPIData($method, $data)
{
$username = "XXXX";
$shared_secret = "XXXX";
$postURL = "https://api3.omniture.com/admin/1.4/rest/?method=";
// Nonce is a simple unique id to each call to prevent MITM attacks.
$nonce = md5(uniqid(php_uname('n'), true));
// The current timestamp in ISO-8601 format
$nonce_ts = date('c');
/* The Password digest is a concatenation of the nonce, it is timestamp and your password
(from the same location as your username) which runs through SHA1 and then through a base64 encoding */
$digest = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));
$rc = new SimpleRestClient();
$rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
//var_dump($o);
$rc -> postWebRequest($postURL .$method, $data);
return $rc;
}
$method = 'Report.Queue';
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
/*
"date":"'.$date.'",
"dateTo":"'.$date.'",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
*/
$rc=GetAPIData($method, $data);
if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
$counter = 0;
do
{
if($counter>0){sleep($sleep = 120);}
$return = GetAPIData('Report.Get', $rc->getWebResponse());
$counter++;
}while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'
//
$json=json_decode($return->getWebResponse());
foreach ($json->report->data as $el)
{
echo $el->name.":".$el->counts[0].":".$el->counts[1]."\n";
// Adding the data in the CSV file without overwriting the previous data
array_push($list, array($el->name, $el->name, $el->counts[0], ($el->counts[1])/($el->counts[2])));
}
}
else
{
echo "Wrong";
}
$fp = fopen($adobe_file, 'w');
foreach ($list as $fields)
{
// Save the data into a CSV file
fputcsv($fp, $fields);
}
fclose($fp);
?>
How can I get the names of the metrics and elements in order to use them in this script? There is no way. I searched with all the possible tags on google and nothing worked !
I need the metrics and elements for this part of the code :
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
I cannot find 'date' as an element which is crucial. I cannot find all the other metrics as well. In Google Analytics we had this link :
Google Analytics Query
but in Adobe there is not any. I want something like that :
"metrics":[{"id":"instances"},{"id":"impressions"}],
"elements":[{"id":"date","top":"50000"}]
You would json_decode() as $data contains a JSON string. For example:
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
$json = json_decode($data, true);
echo $json['reportDescription']['dateFrom'];
print_r($json['reportDescription']['metrics']);

Login with User-Agent as token

I'm working on a website project (PHP, Fat-Free and mongodb) and I have a problem with only one user.
When the user does login, I call this function:
function login() {
$user = F3::get('POST.user');
$pass = F3::get('POST.pass');
if($user!=""&&$pass!=""){
$bcrypt = new Bcrypt(12);
$ismail = strrpos($user, "#");
$loginUser = new HT('user');
if($ismail===false){
$loginUser->load(array('nick' => $user));
}else{
$loginUser->load(array('email' => strtolower($user)));
}
if(!$loginUser->dry()){
if($loginUser->isActive == true){
$isValid = $bcrypt->verify($pass, $loginUser->password);
if($isValid){
$final_token = StringHelper::rand_str(30);
$tmp = $loginUser->token;
if(!is_array($tmp))
$tmp = array();
$cli_id = md5($_SERVER['HTTP_USER_AGENT']);
$tmp[$cli_id] = $final_token;
$loginUser->token = $tmp;
$user_id = $loginUser->_id."";
$loginUser->loginDate = new MongoDate();
$loginUser->updateFromId();
$isPremium = $loginUser->isPremium;
F3::set('user_id', $user_id);
if(isset($loginUser->preferences) && isset($loginUser->preferences['langPref'])){
$lang = $loginUser->preferences['langPref'];
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"$lang","schema"=>"$schema","isPremium"=>$isPremium));
}else{
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"en","schema"=>"$schema","isPremium"=>$isPremium));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}else{
echo json_encode(array("status"=>self::NOT_ACTIVE));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}
}
NOTE: dry() function checks if user is null in mongodb.
The user says that in his office computer can't do login, and he gets and "Invalid password" error. But he can login in the website in any other computer.
Sometimes, if he deletes cache or reset his password can access to the website.
I'm saving in the 'User' mongodb collection an array of tokens like this:
{
........ (Other params),
"token" : {
"d222b6a854d35c9c9584e695b623c468" : "nX0CuAraUQMGm5UsUWhUqZzgXZnapN",
"8c27b0d66a7ea6cec5dda9979cc92bd3" : "swdYhSQN5el0x9Pmn2YXZuwckpmuHP",
"28b825f204e7ebd320756bd6294a29c1" : "UFGd18db8W9gq1WDXgx4F9BZRVRY3K"
}
}
This token array contains:
key: MD5 encrypted User-Agent
value: Random string
This keeps session for different devices and browsers.
Everytime the user wants to do something in the web I put in the route the user id and the token (value), and I check if values are correct:
....
$uid = md5($_SERVER['HTTP_USER_AGENT']);
if(isset($user->token[$uid]) && $user->token[$uid]==$token){
....
return true;
}else{
return false;
}
I thought that the problem was with the User-Agent. Any solution?
Thanks!

Custom Joomla 3 Button task not executing in my controller

I am trying to upload an external list of "groups" to add to my custom Joomla 3 component. I have created a CSV file and written a few functions that I hope will do it. I have created a custom button to start the task in my "groups" view.
When I push the button I get an SQL error that has absoloutle nothing to do with the functions so I have tried debugging and when the button is pressed its not even getting to my controller task before the sql error. I am so confused as to why.
This is the code I have
view.html.php TestViewGroups
JToolBarHelper::custom('group.uploadsave', '', '', 'Upload and Save', false);
TestControllerGroup
protected function uploadsave() {
$detail_headers = array(
'agm_date',
'preferred_media'
);
$rows = array_map('str_getcsv', file('groupdata.csv'));
$header = array_shift($rows);
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$this->saveUploaded($entry);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}
protected function saveUploaded($dataIn = array()) {
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$table = $model->getTable();
$data = $dataIn;
$checkin = property_exists($table, 'checked_out');
// Determine the name of the primary key for the data.
if (empty($key))
{
$key = $table->getKeyName();
}
// To avoid data collisions the urlVar may be different from the primary key.
if (empty($urlVar))
{
$urlVar = $key;
}
$recordId = $this->input->getInt($urlVar);
// Populate the row id from the session.
$data[$key] = $recordId;
if (!$model->save($validData))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
if ($checkin && $model->checkin($validData[$key]) === false)
{
// Save the data in the session.
$app->setUserState($context . '.data', $validData);
// Check-in failed, so go back to the record and display a notice.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
I am not using this as a regular function, its just a once off to upload the data initially.
The SQL error I am getting is like it is trying to load a list of groups?? not anything to do with the save function at all.
The saveUploaded is a similar function to the initial save function.
Thanks :-)
**** Edit *****
I have just followed the task through with debug and its getting to the execute task methotd of JControllerLegacy and because the task is not defined in the task map its defaulting to display, hence the SQL error trying to load a group when it doesn't have an ID. Do I need to now register a task in the task map before it will pick it up?
I am officially an idiot! When I just logged back on to see if anyone had responded I saw that I had declared the function as a protected function!! dir! I just copied and pasted from another function and forgot to change its access. I also made a few other changes and now it works quite well!
public function uploadsave() {
// An array of headers that will need to be entered into a seperate array to allow entry as JSON
$detail_headers = array(
'agm_date',
'preferred_media'
);
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$path = JPATH_COMPONENT . '/controllers/groupdata.csv';
//Load the file and pass each line into an array.
$rows = array_map('str_getcsv', file($path));
//Take out the first line as it is the headers.
$header = array_shift($rows);
//turn each of the arrays into an entry
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
//separate each of the entries that need to be entered into an array to be stored as JSON
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$recordId = 'id';
// Populate the row id from the session.
$entry[$key] = $recordId;
//Save each one
if (!$model->save($entry))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
return false;
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}

Geocoding doesn't work now V3 is in play

I have a internal site which uses php to look through my msql customer database. Find any customers which do not have lat and lng fields filled in. Grab the postcodes and geocode them posting the lat and lng back to my database and plot the customers on the map. This is done by a cron job once a day. This worked fine using v.2 of google api. Since march or april its stopped. Im guessing because of v.3.
Jist my jl_jobscoordinates.cron.php file searches through the database picking up all the postcodes for empty lat and lng fields. Then calls a function from my geocode.class.php called doGeocode which uses xml to put togther and find results and save the lat and lng. Inside the geocodeclass it refers to a m_url which is the googleapi url which is saved inside my config file. I have updated this url to the new v.3 url which is http://maps.googleapis.com/maps/api/geocode/xml?address=%s&sensor=false. My map is back up and running, just nothing will geocode.
I will paste the two files jl_jobscooedinates.cron.php and geocode.class.php. I have commented out the old xml in the geocode which used to work with the old url.
The results of my cron is that it is not getting coordinates. e.g. -- [3-2013] Google could not find this Postcode: [COO041] Test Company Name, Oxfordshire OX26 4SS
jl_jobcoordinates.cron.php
require_once("../includes/config.php");
require_once(_PATH_JMS."/classes/session.class.php");
require_once(_PATH_JMS."/classes/db.class.php");
require_once(_PATH_JMS."/classes/lib.class.php");
require_once(_PATH_JMS."/classes/security.class.php");
require_once(_PATH_JMS."/classes/emails.class.php");
require_once(_PATH_JMS."/classes/geocode.class.php");
require_once(_PATH_JMS."/services/actiontrail.ds.php");
require_once(_PATH_JMS."/services/jobsdue.ds.php");
//-----------------------------------------------------
// Main Object Instances - Initialize what we require
//-----------------------------------------------------
$DB = new DB();
$Security = new Security($DB->i_db_conn);
$Lib = new Lib();
$Session = new Session();
$ActionTrail = new ActionTrail($DB, $Session, $Security);
$JobsDue = new JobsDue($DB, $Session, $Security, $ActionTrail);
$Geocode = new Geocode($Session, $Security);
$Emails = new Emails($DB, $Session, $Security);
//-----------------------------------------------------
// Save as a valid system user
//-----------------------------------------------------
$Session->save('USR_AUTH',_CRON_USER_NAME);
$Session->save('USR_PASS',_CRON_USER_PASS);
$Session->save('USR_IS_EMPLOYED', '1');
$Session->save('CONS',$Session->get('USR_AUTH'));
//-----------------------------------------------------
// Postcodes to Ignore - we cannot geocode these
//-----------------------------------------------------
$m_ignore = array("IRL","IRELAND","IRE","ITA","USA","BEL","EGY","GER","FR","FRA","HOL","POL");
//-----------------------------------------------------
// Get Jobs Due for all consultants for this year and next
//-----------------------------------------------------
$mY = (int) date("Y");
//-----------------------------------------------------
// Find t-cards without lat & lng
//-----------------------------------------------------
$m_errors = array();
for ($y=$mY;$y<=$mY+1;$y++)
{
for ($i=1;$i<=12;$i++)
{
$mM = (int) $i;
//echo "<br> mM =".$mM ." i =".$i;
$mJobs = $JobsDue->getAllJobsDue('%',$mM,$y,'%',NULL,NULL,FALSE); /* DON'T GET MISSED JOBS AS WE WILL START FROM JAN */
//echo "<br>mJobs =".$mJobs;
foreach ($mJobs as $row)
{
$m_postcode = $Lib->lib_str_clean(trim($row->postcode)); //this loops through each of the records and gets the post codes. m_postcodes are the postcodes found
echo "<br>m_postcode =".$m_postcode;
if (($row->latlngexists == 1)||(in_array($m_postcode,$m_ignore))||(in_array($row->card_id,$m_ignore))||(strlen($m_postcode)<=0)) continue;
if ($Lib->lib_ispostcode($m_postcode)) {
$m_coordinates = $Geocode->doGeocode($m_postcode);
echo "<br>m_coords =".$m_coordinates;//nothing displayed
if ($m_coordinates != NULL) {
$DB->setGeoTCard($row->card_id,$m_coordinates['lat'],$m_coordinates['lng']);
} else {
$m_err_desc = sprintf("[%s-%s] Google could not find this Postcode",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
sleep(_GEOCODE_PAUSE);
} else {
$m_err_desc = sprintf("[%s-%s] Postcode is invalid please check",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
}
}
}
if (count($m_errors) > 0) {
$Emails->doGeocodeErrNotify($m_errors);
}
geocode.class.php
class Geocode {
private $m_session = NULL;
private $m_security = NULL;
private $m_session_user;
private $m_session_pass;
private $m_key = _GMAP_KEY;
private $m_url = _GMAP_URL;
private $m_res = Array();
public function __construct($p_session,$p_security)
{
$this->m_session = $p_session;
$this->m_security = $p_security;
$this->m_session_user = $this->m_session->get('USR_AUTH');
$this->m_session_pass = $this->m_session->get('USR_PASS');
if ($this->m_security->doLogin($this->m_session_user,$this->m_session_pass) <= 0)
{
return NULL;
die;
}
}
public function doGeocode($p_postcode)
{
try {
// //$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode,$this->m_key),0,TRUE); //OLD FOR V.2
$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode),0,TRUE);
} catch (Exception $e) {
echo sprintf('Caught exception: %s', $e->getMessage());
return NULL;
die;
}
$st = $xml->Response->Status->code;
if (strcmp($st, "200") == 0)
{
$co = $xml->Response->Placemark->Point->coordinates;
$cs = preg_split("/[\s]*[,][\s]*/", $co);
$this->m_res = Array(
"lng" => $cs[0],
"lat" => $cs[1],
"alt" => $cs[2]
);
return $this->m_res;
} else {
return NULL;
}
}
}
I would really appriciate if someone could help me please. Im guessing its something to do with the new url in my config file and the current xml not set properly for the sensor??
My geocode stuff is still working fine just like this don't forget to use your own personal API key!
/**
* Geocode postcode to get long/lat used when adding suppliers and sites
* #param - $postcode - string - Input post code to geocode
* #return - $lat,$long - array - array containing latitude coords
*/
function geocode($postcode) {
$postcode = urlencode(trim($postcode)); // post code to look up in this case status however can easily be retrieved from a database or a form post
//$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=false"; // the request URL you'll send to google to get back your XML feed
define("MAPS_HOST", "maps.google.co.uk");
define("KEY", "YOUR API KEY HERE");
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
$request_url = $base_url . "&q=" . $postcode;
$xml = simplexml_load_file($request_url);
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = explode(",", $coordinates);
// Format: Longitude, Latitude, Altitude
return array("lat"=>$coordinatesSplit[1],"long"=>$coordinatesSplit[0]);
} else {
return array("lat"=>0,"long"=>0);
}
}

Categories