Clear session after checkout with custom payment method - php

Im using custom payment method for payments with credit and debit cards in OpenCart 2.1.0.1 but I am facing a problem. When I make a successful purchase and I redirected to succsess.tpl page, after that when i continue shopping (in the same browser session) and make a second successful purchase - its not recording as new order with new order id! I will attach my controller, which can be the code for clearing session?
class ControllerPaymentFibank extends Controller {
public function index() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$data['action'] = $this->session->data['order_id'];
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/fibank.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/payment/fibank.tpl', $data);
} else {
return $this->load->view('default/template/payment/fibank.tpl', $data);
}
}
}
public function make_payment() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$ip = $this->get_client_ip();
$amount = $this->currency->format($order_info['total'], 'BGN', '', false);
$amount *= 100;
$post_request="command=v&amount=".$amount."&currency=975&client_ip_addr=".$ip."&description=".$this->session->data['order_id']."&msg_type=SMS";
$res = $this->execute_fibank_query($communication_url, $post_request);
$result = str_replace("TRANSACTION_ID: ", "", $res);
$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], '1', $result);
$_SESSION['order_id']=$this->session->data['order_id'];
header("location:".$payment_url."?trans_id=".rawurlencode($result));
}
exit();
}
public function callback() {
if (isset($this->request->post['trans_id'])) {
$tranz_id = $this->request->post['trans_id'];
} else {
$tranz_id = '';
}
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
if ($tranz_id!="" && $_SESSION['order_id']>0) {
$ip = $this->get_client_ip();
$request="command=c&trans_id=".rawurlencode($tranz_id)."&client_ip_addr=".$ip;
$result = $this->execute_fibank_query($communication_url, $request);
$res = explode("\n", $result);
$fibank_info = str_replace("RESULT: ", "", $res[0]);
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($_SESSION['order_id']);
if ($fibank_info=="OK") {
$order_status = $this->config->get('fibank_order_status_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/successfull-transaction");
}
else{
$order_status = $this->config->get('fibank_order_status_denied_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/transaction-error");
}
}
}
function execute_fibank_query($url, $request){
// debug
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// debug
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $this->config->get('fibank_certificate_path'));
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->config->get('fibank_certificate_pass'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$result = curl_exec($ch);
return $result;
}
function get_client_ip(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}

If you look at the file catalog/controller/checkout/success.php you will see the standard process that follows a successful order. If you've modified this at all, it's possible OpenCart isn't unsetting the session data. In that file, the controller checks if there is data set in the session:
if (isset($this->session->data['order_id'])) {
If it's true, the cart will be cleared with this line:
$this->cart->clear();
And, following the UserActivity logging, the session data is unset with this code:
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
unset($this->session->data['totals']);

Related

How to improve code structure in PHP?

I've created two method in my controller in Laravel to fetch data from another website using PHP CURL and pass to view.
I will used httpData method for initial ID and URL and getHttpCode method to get HTTP_code to find any errors will happen when I fetch data from another website But I don't much understand about this below code performance and how can I testing In PHPstrom to make sure with performance
Here is my function
private function httpData($url =null, $id = null)
{
if($id){
$url = 'http://assignment.gae.golgek.mobi/api/v1/items/'.$id;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 30);
curl_setopt($ch, CURLINFO_HTTP_CODE, true);
curl_setopt($ch, CURLOPT_PRIVATE, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!$executed = curl_exec($ch)) {
$res = $executed;
$data = false;
curl_close($ch);
} else {
if ($this->http_code = $this->getHttpCode(curl_getinfo($ch))) {
$res = $this->http_code;
$data = $executed;
} else {
$res = false;
}
}
return ['s_respond' => $res, 'data' => $executed];
}
private function getHttpCode($http)
{
if (is_array($http)) {
if (!empty($http['http_code'] || $http['http_code'] != 0)) {
return $http['http_code'];
} else {
return false;
}
} else {
return false;
}
}
And I will call this method as below
public function sendData()
{
$url = 'website/api/v1/products';
$data = $this->httpData($url);
return view('products.list', ['data'=>$data]);
}
Thanks for help
I suggest you to addopt the 'early return pattern'.
I did a rewrite in you getHttpCode, it seems more clear to me:
private function getHttpCode($http)
{
if ( !is_array($http)
|| empty($http['http_code'])
|| $http['http_code'] === 0)
{
return false;
}
return $http['http_code'];
}

Is there any TIMEOUT for cURL calls or Symfony2 task execution?

I'm just try to find is there is any TIMEOUT or MAX EXECUTION TIME for execute Symfony2 tasks. Why? Any time I execute the task pdone:sync it stop with this log:
Symfony > pdone:sync
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Undefined offset: 2000
pdone:sync
The command terminated with an error status (1)
This is my code which is called from task as a service and second SOQL query returns exactly 6911 items so it should insert 6911 and not stop at 2000, why? what is happening there? Any advice or help or ideas?
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use PDI\PDOneBundle\Entity;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RequestStack;
class SyncController extends Controller
{
private $_em;
private $_container;
private $_rs;
public function __construct(Container $container, EntityManager $em, RequestStack $rs)
{
$this->_container = $container;
$this->_em = $em;
$this->_rs = $rs;
}
public function syncVeevaData()
{
$em = $this->_em;
$request = $this->_rs->getCurrentRequest();
$container = $this->_container;
// Will need this in the whole function so lets declare it here
$now = new \DateTime();
$expireTime = clone $now;
$expireTime = $expireTime->modify('+1 week');
// Request veeva token and instance URL
$token_url = $container->getParameter('login_uri')."/services/oauth2/token";
$params = "grant_type=".$container->getParameter('grant_type')
."&client_id=".$container->getParameter('client_id')
."&username=".$container->getParameter('veeva_username')
."&password=".$container->getParameter('veeva_password')
."&client_secret=".$container->getParameter('client_secret')
."&redirect_uri=".urlencode($container->getParameter('redirect_uri'));
$curl = curl_init($token_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$response = json_decode($json_response, true);
$veevaToken = $respObj['access_token'] = $response['access_token'];
$instanceUrl = $respObj['instance_url'] = $response['instance_url'];
if (!isset($veevaToken) || $veevaToken == "") {
$respObj['error'] = "Error - access token missing from response!";
return $respObj;
}
if (!isset($instanceUrl) || $instanceUrl == "") {
$respObj['error'] = "Error - instance URL missing from response!";
return $respObj;
}
// Request reps and sync against DB
$soqlQuery1 = "SELECT Id,FirstName,LastName,Username,Email,LastModifiedDate FROM User";
$soqlUrl1 = $instanceUrl.'/services/data/v28.0/query/?q='.urlencode($soqlQuery1);
$curl = curl_init($soqlUrl1);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$soqlObj1 = json_decode($jsonResponse, true);
for ($i = 0; $i < $soqlObj1['totalSize']; $i++) {
$entReps = $em->getRepository('PDOneBundle:Representative')->findOneBy(
array(
'veeva_rep_id' => $soqlObj1['records'][$i]['Id'],
)
);
if (!$entReps) {
// if there is no reps, then we add
$newReps = new Entity\Representative();
// we set the values from veeva
$newReps->setVeevaRepId($soqlObj1['records'][$i]['Id']);
$newReps->setEmail($soqlObj1['records'][$i]['Email']);
$newReps->setFirst($soqlObj1['records'][$i]['FirstName']);
$newReps->setLast($soqlObj1['records'][$i]['LastName']);
$newReps->setUsername($soqlObj1['records'][$i]['Username']);
$newReps->setLastLoginAt($now);
$newReps->setLastSyncAt($now);
$newReps->setDisplayName(
$soqlObj1['records'][$i]['FirstName'].' '.$soqlObj1['records'][$i]['LastName']
);
$newReps->setRepType("VEEVA");
$em->persist($newReps);
$em->flush();
// Put new reps into $newRepsArr
$repsArr[$newReps->getId()] = $newReps->getVeevaRepId();
} else {
$lastModifiedDate = new \DateTime(
$soqlObj1['records'][$i]['LastModifiedDate']
);
if ($lastModifiedDate > $entReps->getLastSyncAt()) {
// obtained a reps, we update its data
$entReps->setEmail($soqlObj1['records'][$i]['Email']);
$entReps->setFirst($soqlObj1['records'][$i]['FirstName']);
$entReps->setLast($soqlObj1['records'][$i]['LastName']);
$entReps->setUsername($soqlObj1['records'][$i]['Username']);
$entReps->setLastLoginAt($now);
$entReps->setLastSyncAt($now);
$entReps->setDisplayName(
$soqlObj1['records'][$i]['FirstName'].' '.$soqlObj1['records'][$i]['LastName']
);
$entReps->setRepType("VEEVA");
// Put updated reps into $updRepsArr
$repsArr[$entReps->getId()] = $entReps->getVeevaRepId();
}
}
}
$em->flush();
// Get territories and sync against DB
$soqlQuery2 = "SELECT Id,Name,LastModifiedDate FROM Territory";
$soqlUrl2 = $instanceUrl.'/services/data/v28.0/query/?q='.urlencode($soqlQuery2);
$curl = curl_init($soqlUrl2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$soqlObj2 = json_decode($jsonResponse, true);
for ($i = 0; $i < $soqlObj2['totalSize']; $i++) {
$entTerritory = $em->getRepository('PDOneBundle:Territory')->findOneBy(
array(
'veeva_territory_id' => $soqlObj2['records'][$i]['Id']
)
);
if (!$entTerritory) {
// if there is no territory, then we add
$newTerritory = new Entity\Territory();
// we set the values from veeva
if ($soqlObj2['records'][$i]['Id'] !== null || $soqlObj2['records'][$i]['Id'] !== "") {
$newTerritory->setVeevaTerritoryId($soqlObj2['records'][$i]['Id']);
$newTerritory->setName($soqlObj2['records'][$i]['Name']);
$em->persist($newTerritory);
$em->flush();
}
$terrArr[] = $newTerritory->getId();
$terrFailArr[] = $soqlObj2['records'][$i]['Name'];
} else {
$lastModifiedDate = new \DateTime(
$soqlObj2['records'][$i]['LastModifiedDate']
);
if ($lastModifiedDate > $entTerritory->getUpdatedAt()) {
// obtained a territory, we update its data
$entTerritory->setName($soqlObj2['records'][0]['Name']);
}
$terrArr[] = $entTerritory->getId();
}
}
$em->flush();
return $respObj;
}
}

How to develop user defined menu on wechat

here is my sample code. my developer mode is already enabled but there is no menu tabs options.
you can also add me on wechat so I can elaborate my problems in this matter, here is my wechat ID VinceZen. I badly need some help guys. Thank you in advance.
<?php
$data[] = '772134292672v';
$data[] = $_GET['timestamp'];
$data[] = $_GET['nonce'];
asort($data);
$strData = '';
$d = '';
$authString = '';
foreach($data as $d)
{
$authString .= $d;
}
//verify the signature
if(sha1($authString) == $_GET['signature'])
{
//check the echostr
if(!empty($_GET['echostr']))
{
echo $_GET['echostr'];
die();
}
else
{
//logic
//Getting access_token from customize menus
static function get_access_token($appid,$secret){
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json=http_request_json($url);//here cannot use file_get_contents
$data=json_decode($json,true);
if($data['access_token']){
return $data['access_token'];
}else{
return "Error occurred while geting the access_token";
}
}
//Though URL request is https',cannot use file_get_contents.Using CURL while asking the JSON data
function http_request_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$return = "<xml>
<ToUserName><![CDATA['.$toUser.']]</ToUserName>
<FromUserName><![CDATA['.$fromUser.']]</FromUserName>
<CreateTime>'.time.'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.text.']]</Content>
<FuncFlag>0</FuncFlag>
</xml>";
echo $return;
{
"button":[
{
"type":"click",
"name":"Daily Song",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":" Artist Profile",
"key":"V1001_TODAY_SINGER"
},
{
"name":"Menu",
"sub_button":[
{
"type":"view",
"name":"Search",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"Video",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"Like us",
"key":"V1001_GOOD"
}]
}]
}
}
}
else
{
die('Access Denied');
}`enter code here`
?>

reverse geocoding not working, Google Maps API v2

I'm using google maps api v2 and I am sending coordinates to my program. The localisation on the map works fine but I never get the adress...
Here is my class:
class reverseGeoCoding {
//put your code here
private $result;
private $latitude=null;
private $longitude=null;
private $adresse=null;
private $config;
public $contents;
function xml2ary(&$string) {
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);
$mnary=array();
$ary=&$mnary;
foreach ($vals as $r) {
$t=$r['tag'];
if ($r['type']=='open') {
if (isset($ary[$t])) {
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_c']=array();
$cv['_c']['_p']=&$ary;
$ary=&$cv['_c'];
} elseif ($r['type']=='complete') {
if (isset($ary[$t])) { // same as open
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_v']=(isset($r['value']) ? $r['value'] : '');
} elseif ($r['type']=='close') {
$ary=&$ary['_p'];
}
}
$this->del_p($mnary);
return $mnary;
}
// _Internal: Remove recursion in result array
function del_p(&$ary) {
foreach ($ary as $k=>$v) {
if ($k==='_p') unset($ary[$k]);
elseif (is_array($ary[$k])) $this->del_p($ary[$k]);
}
}
// Array to XML
function ary2xml($cary, $d=0, $forcetag='') {
$res=array();
foreach ($cary as $tag=>$r) {
if (isset($r[0])) {
$res[]=ary2xml($r, $d, $tag);
} else {
if ($forcetag) $tag=$forcetag;
$sp=str_repeat("\t", $d);
$res[]="$sp<$tag";
if (isset($r['_a'])) {
foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";
}
$res[]=">".((isset($r['_c'])) ? "\n" : '');
if (isset($r['_c'])) $res[]=ary2xml($r['_c'], $d+1);
elseif (isset($r['_v'])) $res[]=((!is_numeric($r['_v'])&&$r['_v']) ? '<![CDATA[' : false).$r['_v'].((!is_numeric($r['_v'])&&$r['_v']) ? ']]>' : false);
$res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
}
}
return implode('', $res);
}
function formatGmapXML($xml,$returnXML=false,$error=false) {
$tmp = array();
$tmp['request']= $xml['kml']['_c']['Response']['_c']['name']['_v'];
$tmp['status']= $xml['kml']['_c']['Response']['_c']['Status']['_c']['code']['_v'];
// check our Response code to ensure success
if($tmp['status']=='200') {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['Point']['_c']['coordinates']['_v'];
if($tmp['addressFull']==null) {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['Point']['_c']['coordinates']['_v'];
}
$latlng = explode(',',$tmp['coordinates']);
$tmp['latitude'] = $latlng[1];
$tmp['longitude'] = $latlng[0];
}
// optional outputs
if($error) $tmp['error'] = $error;
if($returnXML) $tmp['xml'] = ary2xml($xml);
return $tmp;
}
/*
$q=$_GET['q'];
$latitude=$_GET['latitude'];
$longitude=$_GET['longitude'];
*/
function reverseGeoCoding() {
$this->config=new configInt();
}
function setLongitude($longitude) {
$this->longitude=$longitude;
}
function setLatitude($latitude) {
$this->latitude=$latitude;
}
function setadresse($adresse) {
$this->adresse=$adresse;
}
function getLongitude() {
return $this->longitude;
}
function getLatitude() {
return $this->latitude;
}
function getadresse() {
return $this->adresse;
}
function exec() {
if($this->longitude && $this->latitude ) {
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&ll={$this->latitude},{$this->longitude}&key={$this->config->clefGoogle}");
}else {
$adresse=rawurlencode($this->adresse);
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&q={$adresse}&key={$this->config->clefGoogle}");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
//curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_VERBOSE, false);
$this->contents=curl_exec($ch);
$this->contents=$this->xml2ary($this->contents);
$this->result=$this->formatGmapXML($this->contents,false);
curl_close($ch);
if($this->longitude && $this->latitude ) {
$this->adresse=utf8_decode($this->result['addressFull']);
}else {
$this->latitude=$this->result['latitude'];
$this->longitude=$this->result['longitude'];
}
return $this->result;
}
}
?>
I'm using getAdress in my programm to save the adress in the database, but it never seems to work properly even though the coordinates are correct...
Try this:
$result = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true'));
echo $result->results[0]->formatted_address;
function getaddress($lat, $lng) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . trim($lat) . ',' . trim($lng) . '&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if ($status == "OK")
return $data->results[0]->formatted_address;
else
return false;
}

Curl error Could not resolve host: saved_report.xml; No data record of requested type"

<?php
error_reporting(E_ALL);
$url = 'saved_report.xml';
define('XML_HEADER', '*RWRESPONSE*RESPONSE*DATA*HEADER*COLUMN');
define('XML_ROW', '*RWRESPONSE*RESPONSE*DATA*ROW*COLUMN');
$headers = array();
$rows = array();
function startTag($parser, $data) {
global $current_tag;
$current_tag .= "*$data";
}
function endTag($parser, $data) {
global $current_tag;
$tag_key = strrpos($current_tag, '*');
$current_tag = substr($current_tag, 0, $tag_key);
}
function contents($parser, $data) {
global $current_tag, $headers, $rows;
switch($current_tag) {
case XML_HEADER:
array_push($headers, $data);
break;
case XML_ROW:
array_push($rows, $data);
break;
}
}
// fetch the report
$curl_object = curl_init();
curl_setopt($curl_object, CURLOPT_URL, $url);
curl_setopt($curl_object, CURLOPT_HEADER, 0);
curl_setopt($curl_object, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_object, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_object, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($curl_object);
$error = curl_error($curl_object);
$info = curl_getinfo($curl_object);
curl_close($curl_object);
if ($error) {
die("An error occured while fetching the report\n");
}
// process the report
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");
if(!(xml_parse($xml_parser, $result))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
for($i = 0; $i \n";
}
echo '';
echo "$headers[3]: $rows[3]\n";
echo "$headers[4]: $rows[4]\n";
?>
while running this script , i am getting an error
"Could not resolve host: saved_report.xml; No data record of requested type"
i am not able to resolve this .
You need to specify full path of the file, e.g.:
$url = 'http://example.com/saved_report.xml';
as curl doesn't work with relative URLs

Categories