help with php and xml for yahoo service - php

I am working on a PHP code for my social network, what I am planning to do is on user signup or profile update
I will take there zipcode that they enter and use yahoo to lookup there lattitude and logitude from there zipcode
I will then save these value to there user mysql table, this will be used later on to find users located within X amount
of miles from them.
Here is my code so far to get this info before storing into DB
<?PHP
function yahoo_geo($location) {
$q = 'http://api.local.yahoo.com/MapsService/V1/geocode';
q .= '?appid=rlerdorf&location='.rawurlencode($location);
echo $q;
libxml_use_internal_errors(true);
$xml = simplexml_load_file($q);
if(!is_object($xml)) return false;
$ret['precision'] = (string)$xml->Result['precision'];
foreach($xml->Result->children() as $key=>$val) {
if(strlen($val)){
$ret[(string)$key] = (string)$val;
}
return $ret;
}
$_REQUEST['location'] = 32744; // my zip code
$a = yahoo_geo($_REQUEST['location']);
// set retunred data to some variables for storage into MySQL
$latitude = $a[Latitude];
$longitude = $a[Longitude];
// MySQL code will go here
// Output for demo
echo 'Lattitude' .$latitude. '<BR><BR>';
echo 'Longitude' .$longitude. '<BR><BR>';
?>
This works great except if a long. and lat. is not found it returns an error to the browser
Warning: simplexml_load_file(http://api.local.yahoo.com/MapsService/V1/geocode?appid=rlerdorf&location=some non zipcode) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\webserver\htdocs\test\geolocation\index.php on line 16
Note; I could make sure that zipcode is numeric only but I would rather not as yahoo will let me search with other fields as well, so If a user does not enter a zipcode I will make it use a city or state or even country at the worse case so every user should have some sort of longitude and lat. saved
Is there a good way to avoid the error showing or even better is there a way to detect id there is an error and if an error occurs I could insert a default value for that user?

Not exactly sure what your question is, but I think you're looking for the error control operator #
xml = #simplexml_load_file($q);
Your function will then return false as normal.
You need to check that later though (and add some quotes):
if (!$a)
{
// Do something
}
else
{
$latitude = $a['Latitude'];
$longitude = $a['Longitude'];
}

With the # operator :
you have to use it everytime you need it
when you want to debug, you have to remove it from everywhere (or use the scream extension -- which you cannot always install, depending on your hosting service)
if there is an error somewhere you didn't put #, it will still be displayed to the user.
Another solution would be to use something like this at the beginning of your script, when you are on the production server :
ini_set('display_errors', 'Off');
That way, no error is ever displayed to the end-user (they don't need to see those, and probably wouldn't understand), even in situations you didn't think about ; and it's easy to get all the errors displayed on your development machine : just on line to comment ;-)
Note : in production, if you can set the configuration like you want, there is the possibility to log errors to a file ; that way, you can check those, and not have them displayed.

Related

Is it possible to output certain content on a php document and make it die only if it’s URL is present with a value of true on a MySQL database?

I am trying to setup a PHP document but I currently am looking for a way to use the die() function and display some content on every page using my global configuration file. The way I am think how it should work is that IF the requested URL (e.g. domain.com/services/disabledservice) would have /services/disabled service and a value of 1 to make the value true in a MYSQL DB.
The plan is to have the URL be collected and checked with a table than if the row has a value of 1 for status it will display a disabled page message but if it’s 0 it will load normally.
Some research I have conducted may lead be to think that using the SQL query and the if function could work for this.
The idea I have is this but it may not be correct.
<?php $pageurl = [requested URL content here]
$checkstatus = "SELECT * FROM servicestatus WHERE page =" . $pageurl . "AND status = 1";
if ($status = mysqli_query($conn, $servicestatus)) {
if (mysqli_num_rows($status) = 1) { ?> html content here
<?php }
} else { ?>
page as normal
<?php } ?>
Edit:
To explain what I am trying to do.. I am trying to fetch the URL without everything past “?” Than I am trying to use that in a DB query to check with the database if that has a value of “m” or “d” and if it has one of those values next to the URL which is being fetched it will display the appropriate error page. This is being included as part of my core configuration file which includes my “$conn” and the core values for most stuff. The problem I am facing is that when I send my URL without everything past the “?” I am not receiving my error page and everything is loading like normal.
Use any one the following php functions:
include 'path_to_the_page.php' (or) require 'path_to_the_page.php';
The difference between include and require arises when the file being included cannot be found: include will emit a warning ( E_WARNING ) and the script will continue, whereas require will emit a fatal error ( E_COMPILE_ERROR ) and halt the script.

Clickatell parseReplyCallback returning null?

I am trying to get a reply text message from Clickatell using their Rest API, when I call the parseReplyCallback function when their system posts to my page - it seems to be null or I am not sure how to get the variables it is returning. What I would like to do is have all of the variables returned insert into a SQL database so I can use it elsewhere.
I have tried quite a few things, using various styles of getting the variables such as $_POST, $results['text'], $results->text, and so forth each time I can't seem to get any information out of it. I can't just var_dump or anything because I can't see any backend or console so I am pretty much in the blind, hoping someone else is using this system and has it working fine.
require __DIR__.'/clickatell/src/Rest.php';
use clickatell\ClickatellException;
use clickatell\Rest;
$Rest = new Rest("j8VKw3sJTZuVfQGVC7jdhA");
// Incoming traffic callbacks (MO/Two Way callbacks)
$Rest->parseReplyCallback(function ($result) {
//mysqli_query($con,"INSERT INTO `SMSCHAT` (`text`) VALUES ('$result')");
$mesageId = mysqli_real_escape_string($con,$result['messageId']);
$text = mysqli_real_escape_string($con,$result['text']);
$replyMessageId = mysqli_real_escape_string($con,$result['replyMessageId']);
$to = mysqli_real_escape_string($con,$result['toNumber']);
$from = mysqli_real_escape_string($con,$result['fromNumber']);
$charset = mysqli_real_escape_string($con,$result['charset']);
$udh = mysqli_real_escape_string($con,$result['udh']);
$network = mysqli_real_escape_string($con,$result['network']);
$keyword = mysqli_real_escape_string($con,$result['keyword']);
$timestamp = mysqli_real_escape_string($con,$result['timestamp']);
//do mysqli_query
});
I'd like for it to break the result into individual variables (because I plan on doing other things such as an auto-reply, etc) and upload it to the SQL database scrubbed.
Either doesn't create the table entry or gives me a blank one altogether in that first test where I put the result in the text field.
From a Clickatell point of view, although we understand what you're asking - it's unfortunately outside the scope of support that we offer on our products.
If you would like more information on our REST API functionality, please feel free to find it here: https://www.clickatell.com/developers/api-documentation/rest-api-reply-callback/
If you don't succeed in setting up the callbacks, please feel free to log a support ticket here: https://www.clickatell.com/contact/contact-support/ and one of our team members will reach out and try to assist where possible.

Get region name using MaxMind's GeoLite

I'm a bit confused by how to get the region name and cannot find any documentation on it.
I have the database installed wich it 'GeoIP.dat' and 'geoip.inc' in this directory '...IP GeoLite\GeoLite' and i also have a php page for the test \IP GeoLite\find.php
the code inside the 'find.php' page is it didn't work :
<?php
/* Instead of having to determine the country of the client every time they visit the site we are going to set
a cookie so that any other script in PHP or Javascript can use the region information.
The user is also given a menu option to change the region and reset the cookie to a new value.
Likewise, if it already exists we don't want to change it.
We start off by checking that the cookie called Region exists.
If it does, the job is nearly done and we simply set the $Region variable so that we can refresh
the cookie at the end of the program by recreating it. */
if(isset($_COOKIE['Region']))
{
$Region = $_COOKIE['Region'];
}
else
/* Only if the cookie isn't set do we do the actions in the else part of the if,
so this makes the whole thing efficient.
To make use of the GeoLite code we have to load the include file: */
{
$GeoPath= 'GeoLite/';
include($GeoPath.'geoip.inc');
}
$countrydata = GeoIP_region_name_by_code(gir->country_code, gir->region) ;
echo $countrydata ;
?>
You must open the Geo IP binary data file first
// Open Geo IP binary data file
$geoIp = geoip_open($GeoPath.'GeoIP.dat',GEOIP_STANDARD);
Look at this documentation http://www.maxmind.com/download/geoip/api/php.old/README

PHP how to make an uploaded file link is internal ip when internally and public ip when in public with this snippet i got?

I am doing a php portal.
i did an announcement section where user can post message and attach a file.
so in this situation, a user has uploaded one and at the page, there will be a hyperlink for the attachment. if i hover on it, i can see this "192.168.0.100/Announcement/file.pdf"
so logically if im in the internal network and click on that it would not be a problem as it can get the file from that ip.
next situation is i have forwarded the server ip so that public can access from outside. now i'm as a user accessing from outside.
so if i were to go to the announcement location and hover on it again it will show the same link "192.168.0.100/Announcement/file.pdf". I will definitely wont be able to open it as that ip is internal.
so i am thinking how can i make it when i'm internal, the ip is the internal one and when im outside,the ip link would be the public?
i got this snippet from a ex colleague but i dont really know what the code does. Can someone help me explain this? i tried searching this thing i want to do on the net,but i dont have a proper keyword for it.
below is the snippet:
<?php
//filename constant.php
define('SERVERIP',((preg_match("/^192\.168/i",$_SERVER['REMOTE_ADDR']))?'192.168.0.100':'175.136.xxx.xxx'),true);
?>
And below is part of the code in the page for the announcement and attachment:
include('_include/constant.php');
$dir = "C:/Inetpub/wwwroot/Announcement/";
$http = sprintf('http://%s/Announcement/',SERVERIP);
print '<td class="middle '.$CLASS.'" align="left" height="20">'.''.$filename .'</td>';
Can any php pros here help me to understand whats happening so that next time i know what i'am actually implementing?
You do not need to implement any of this... you need to change how you are referencing the URLs and everything else will fall into place. For example, this will show http://192.168.0.100/ when you are on the LAN in your company. When you access this website from the outside, it will show the IP address or domain name you are accessing from outside.
You should be using...
something PDF
as opposed to:
<a href="http://192.168.0.100/something.pdf>something PDF</a>
which is what it seems like you're doing.
What you have is a ternary operation, the results of which are being assigned to the constant SERVERIP. It is using a regex to match against the $_SERVER['REMOTE_ADDR'], if it begins with 192.168, then it gets the 192.168 value, otherwise it gets the 175.136 value. And for some reason it is passing true to enforce a case insensitive search.
You can read more on define within the PHP docs.
Lighter example of ternary op:
$overlyComplex = true;
$thatDudesCodeSucks = (true === $overlyComplex) ? 'yes' : 'no';
// Shorthand for
if (true === $overlyComplex) {
$thatDudesCodeSucks = 'yes';
} else {
$thatDudesCodeSucks = 'no';
}
var_dump($thatDudesCodeSucks); // echos yes

How to track users location / region in PHP

I'm trying to get the country from which the user is browsing the website so I can work out what currency to show on the website. I have tried using the GET scripts available from: http://api.hostip.info but they just return XX when I test it.
If anyone knows any better methods please share.
Thanks.
I use this:
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
$ip = $_SESSION['ip'];
$try1 = "http://ipinfodb.com/ip_query.php?ip=".$ip."&output=xml";
$try2 = "http://backup.ipinfodb.com/ip_query.php?ip=".$ip."&output=xml";
$XML = #simplexml_load_file($try1,NULL,TRUE);
if(!$XML) { $XML = #simplexml_load_file($try2,NULL,TRUE); }
if(!$XML) { return false; }
//Retrieve location, set time
if($XML->City=="") { $loc = "Localhost / Unknown"; }
else { $loc = $XML->City.", ".$XML->RegionName.", ".$XML->CountryName; }
$_SESSION['loc'] = $loc;
Try these:
http://ip-to-country.webhosting.info/
http://www.ip2location.com/
Both are IP address-to-country databases, which allow you to look up the country of origin of a given IP address.
However it's important to note that these databases are not 100% accurate. They're a good guide, but you will get false results for a variety of reasons.
Many people use proxying to get around country-specific blocks and filters.
Many IP ranges are assigned to companies with large geographic spread; you'll just get the country where they're based, not where the actual machine is (this always used to be a big problem for tracking AOL users, because they were all apparently living in Virginia)
Control of IP ranges are sometimes transferred between countries, so you may get false results from that (especially for smaller/less well-connected countries)
Keeping your database up-to-date will mitigate some of these issues, but won't resolve them entirely (especially the proxying issue), so you should always allow for the fact that you will get false results.
You should use the geoip library.
Maxmind provides free databases and commercial databases, with a difference in the date of last update and precision, the commercial being of better quality.
See http://www.maxmind.com/app/geolitecountry for the free database.
I think it should be sufficient for basic needs.
You can use Geolocation to get the Coordinates and then some Service to get the Country from that, but the geolocation API is browser based so you can only access it via JavaScript and then have to pass theese Informations to PHP somehow, i wrote something on the JS Part once:
http://www.lautr.com/utilizing-html5-geolocation-api-and-yahoo-placefinder-example
When it comes to getting the Location via the IP, there are a bazillion Services out there who offer databases for that, some free, some for charge, some with a lot of IP's stored and much data, some with less, for example the one you mentioned, works just fine:
http://api.hostip.info/?ip=192.0.32.10
So You can ether go with the Geolocation API which is pretty neat, but requires the users permission, works via JS and doesnt work in IE (so far) or have to look for a IPÜ Location Service that fits your needs :)
Try these:
$key="9dcde915a1a065fbaf14165f00fcc0461b8d0a6b43889614e8acdb8343e2cf15";
$ip= "198.168.1230.122";
$url = "http://api.ipinfodb.com/v3/ip-city/?key=$key&ip=$ip&format=xml";
// load xml file
$xml = simplexml_load_file($url);
// print the name of the first element
echo $xml->getName() . "";
// create a loop to print the element name and data for each node
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
There are many ways to do it as suggested by those earlier. But I suggest you take a look at the IP2 PHP library available at https://github.com/ip2iq/ip2-lib-php which we developed.
You can use it like below:
<?php
require_once("Ip2.php");
$ip2 = new \ip2iq\Ip2();
$country_code = $ip2->country('8.8.8.8');
//$country_code === 'US'
?>
It doesn't need any SQL or web service lookup just a local data file. It is faster than almost all other methods out there. The database is updated monthly you can download it for free.
The only thing you will need to do for now if you need the country name in your language is map it to an associative array from something like this https://gist.github.com/DHS/1340150

Categories