PHP to return gethostbyname($lookup) value - php

I am using the code below (simplified version) to determine if my IPs are on a blacklist. I need to modify it to be able to determine if an IP is on a Whitelist. The function will require me to see a specific code returned.
127.0.0.1
127.0.0.2
127.0.0.3
127.0.0.4
127.0.0.5
How can this be adjusted to return the (code) output value when the script runs?
$host = '222.22.222.222';
$rbl = 'hostkarma.junkemailfilter.com';
$rev = array_reverse(explode('.', $host));
$lookup = implode('.', $rev) . '.' . $rbl;
if ($lookup != gethostbyname($lookup)) {
echo "ip: $host is listed in $rbl\n";
} else {
echo "ip: $host NOT listed in $rbl\n";
}
EDIT: Sorry guys, The function of the script above will return confirmation if the IP address is on the blacklist entered in $rlb. However, Hostkarma returns a code, one of the 127.0 codes shown above as each code indicates a different block status. I need to get the code. "echo $lookup;" just returns the reverse lookup, like this: 222.222.22.222.hostkarma.junkemailfilter.com

$lookup = implode('.', $rev) . '.' . $rbl;
$value = gethostbyname($lookup);
if ($lookup != $value){
echo "ip: $host is listed in $rbl\n";
echo "return value: $value\n";
}
else{
echo "ip: $host NOT listed in $rbl\n";
}
The 127.x.x.x code should be given to you as the value returned by gethostbyname.

Do you mean this?
echo $lookup;

Related

Php tracking own location gives a randomized IP

-- Please scroll down to where I marked the PHP --
To explain in better detail.
I made a Leaflet map and in that map I want to load my own location.
Here's my code for that in Javascript, but this is out of question like #Pocketsand and I already discussed. So then scroll down to the PHP code and see if you can get the IP address through the browser.
$part_content = "<div id=\"mapid\"></div>";
//.setView([".$longitude.", ".$latitude."], ".$zoom_factor.");
$part_content .= "<script>
var map = L.map('mapid').fitWorld();
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng).addTo(map)
.bindPopup(\"You are within \" + radius + \" meters from this point\").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
function onLocationError(e) {
alert(e.message);
}
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({setView: true, maxZoom: 16});
</script>";
It's the same code as in this maps source code.
When I go to Firefox, it partly works and on someone else's computer it works fine, when on my computer I get the error from the image I showed you.
So I can't locate on my computer to my own location, as in google maps it works perfectly and my extensions also don't seem to block that part.
PHP:
Basically this:
$ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
Gives me a random IP, because of HTTP_X_FORWARDED_FOR and REMOTE_ADDR gives me the correct IP, but not when I use this from a different IP address then the local one... thats why I check if the proxy is not empty.
This is the full php code for the tracker:
$ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$url = "http://freegeoip.net/json/$ip";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch);
if ($data) {
$location = json_decode($data);
$longitude = $location->longitude;
$latitude = $location->latitude;
$longitude = str_replace(",", ".", $longitude);
$latitude = str_replace(",", ".", $latitude);
}
My current problem is:
$ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDE‌​D_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
Which gets the correct IP address, but it almost seems like it gets the IP hosts location. Which is not my intention, I intend to get the clients location through the IP address, which currently isn't working.
I tried and tried, but couldn't seem to figure this out and hope you guys know more about this.
Thanks in advance!
I am guessing you didn't visit the URL in the error message? It's a Chrome security thing, try running off a local webserver or getting a https certificate on your remote server.
The Chrome Security team and I propose that, for new and particularly
powerful web platform features, browser vendors tend to prefer to make
the the feature available only to secure origins by default.
[...]
Definitions:
“Secure origins” are origins that match at least one of the following
(scheme, host, port) patterns:
(https, *, *)
(wss, *, *)
(*, localhost, ) (, 127/8, *)
(*, ::1/128, *)
(file, *, —)
(chrome-extension, *, —)
This list may be incomplete, and may need to be changed.
Source: https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
To get a client public ip address, in PHP 5.3 or greater use:
<?php
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
?>
And if that is not working, use an external provider like https://geolocation-db.com
A JSON-P callback example:
<?php
$jsonp = file_get_contents('https://geolocation-db.com/jsonp');
$data = jsonp_decode($jsonp);
print $data->IPv4 . '<br>';
print $data->country_code . '<br>';
print $data->country_name . '<br>';
print $data->state . '<br>';
print $data->city . '<br>';
print $data->postal . '<br>';
print $data->latitude . '<br>';
print $data->longitude . '<br>';
// Strip callback function name and parenthesis
function jsonp_decode($jsonp) {
if($jsonp[0] !== '[' && $jsonp[0] !== '{') {
$jsonp = substr($jsonp, strpos($jsonp, '('));
}
return json_decode(trim($jsonp,'();'));
}
?>
And a JSON example:
<?php
$json = file_get_contents('https://geolocation-db.com/json');
$data = json_decode($json);
print $data->country_code . '<br>';
print $data->country_name . '<br>';
print $data->state . '<br>';
print $data->city . '<br>';
print $data->postal . '<br>';
print $data->latitude . '<br>';
print $data->longitude . '<br>';
print $data->IPv4 . '<br>';
?>
Instead of going with a PHP function I did a leaflet function instead, which tracks the user through the browser.
Using the library: leaflet.locate
Where then I could use the:
// create control and add to map
var lc = L.control.locate().addTo(map);
// request location update and set location
lc.start();
But this isn't the answer to the PHP part of my code, even though this leaflet function also works for now.
Sadly the PHP part can't find the exact address through the IP if the server is at another place, but the leaflet way of doing it through the browser does work. Hope you guys find use in these answers.

Why is only one cookie saved when live?

I have a php script handling an incoming ajax request. It looks up some credentials from text files and if they match requirements it sets two cookies, one called username and one called creds on the client machine.
When I do this from my local web server, all three cookies get set and I receive all the php feedback from the echoes.
When I do this from my hosted web server the first setcookie works ("cookies","enabled") but the next two dont! However I get all the echoes confirming that php has reached the point in my script where they should be set. Any ideas please? I am thoroughly stumped.
<?php
//george:bloog
//emeline:sparg
setCookie("primacy[cookies]","enabled", time()+3600*24*30,'/');
//convert string to summed int
function pwdInt($pw)
{
$pwdIntVal = 0;
for($i=0; $i<strlen($pw);$i++)
{
$pwdIntVal = $pwdIntVal + ( ord(strtolower($pw[$i])) - 96 );
}
return $pwdIntVal;
}
//retrieve user account creation date by parsing savefile for accountCreate var
function getACD($aUSR)
{
$saveFileName = "saveFiles/" . $aUSR . ".txt";
echo "Fetched save successfully.<br>";
$lines = file($saveFileName);
foreach($lines as $line)
{
if( explode(":",$line)[0] == "accountCreate");
$lineDate = explode(":",$line)[1];
return $lineDate;
}
}
//accept incoming vars
if(isset($_POST['username']) && !empty($_POST['username']))
{
$uN = strtolower($_POST['username']);
$pwd = strtolower($_POST['password']);
$found = "Invalid user";
//test for presence in creds
$lines = file("creds/creds.txt");
foreach($lines as $line)
{
$lineName = explode("_",$line)[0];
if($uN == $lineName)
{
//matched username before delimiter "_"
$found = $lineName;
echo "Found user, " . explode("_",$line)[0] . " checking password<br>";
//check two: use int of pwd with account creation date from user save
$usrACD = getACD($uN);
echo $usrACD;
if( (pwdInt($pwd) * $usrACD) == (explode("_",$line)[1]) )
{
echo "Tests passed: granting access cookies";
setCookie("uN",$uN, time()+3600*24*30,'/');
setCookie("cred",(pwdInt($pwd) * $usrACD), time()+3600*24*30,'/');
}
else
{
echo "Failed password check for allowed user<br>";
}
}
}
}
else
{
echo $found . pwdInt($pwd) . "<br>";
}
?>
You should either enable output buffering or move echoes after setCookie method. Setting cookies is thing that happens during headers of response. All headers should be sent before content. Echoing things is setting up content, so every header edition (like setting cookies) after first echo will fail.

PHP Strip domain name from url

I know there is a LOT of info on the web regarding to this subject but I can't seem to figure it out the way I want.
I'm trying to build a function which strips the domain name from a url:
http://blabla.com blabla
www.blabla.net blabla
http://www.blabla.eu blabla
Only the plain name of the domain is needed.
With parse_url I get the domain filtered but that is not enough.
I have 3 functions that stips the domain but still I get some wrong outputs
function prepare_array($domains)
{
$prep_domains = explode("\n", str_replace("\r", "", $domains));
$domain_array = array_map('trim', $prep_domains);
return $domain_array;
}
function test($domain)
{
$domain = explode(".", $domain);
return $domain[1];
}
function strip($url)
{
$url = trim($url);
$url = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
$url = preg_replace("/\/.*$/is" , "" ,$url);
return $url;
}
Every possible domain, url and extension is allowed. After the function is finished, it must return a array of only the domain names itself.
UPDATE:
Thanks for all the suggestions!
I figured it out with the help from you all.
function test($url)
{
// Check if the url begins with http:// www. or both
// If so, replace it
if (preg_match("/^(http:\/\/|www.)/i", $url))
{
$domain = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
}
else
{
$domain = $url;
}
// Now all thats left is the domain and the extension
// Only return the needed first part without the extension
$domain = explode(".", $domain);
return $domain[0];
}
How about
$wsArray = explode(".",$domain); //Break it up into an array.
$extension = array_pop($wsArray); //Get the Extension (last entry)
$domain = array_pop($wsArray); // Get the domain
http://php.net/manual/en/function.array-pop.php
Ah, your problem lies in the fact that TLDs can be either in one or two parts e.g .com vs .co.uk.
What I would do is maintain a list of TLDs. With the result after parse_url, go over the list and look for a match. Strip out the TLD, explode on '.' and the last part will be in the format you want it.
This does not seem as efficient as it could be but, with TLDs being added all the time, I cannot see any other deterministic way.
Ok...this is messy and you should spend some time optimizing and caching previously derived domains. You should also have a friendly NameServer and the last catch is the domain must have a "A" record in their DNS.
This attempts to assemble the domain name in reverse order until it can resolve to a DNS "A" record.
At anyrate, this was bugging me, so I hope this answer helps :
<?php
$wsHostNames = array(
"test.com",
"http://www.bbc.com/news/uk-34276525",
"google.uk.co"
);
foreach ($wsHostNames as $hostName) {
echo "checking $hostName" . PHP_EOL;
$wsWork = $hostName;
//attempt to strip out full paths to just host
$wsWork = parse_url($hostName, PHP_URL_HOST);
if ($wsWork != "") {
echo "Was able to cleanup $wsWork" . PHP_EOL;
$hostName = $wsWork;
} else {
//Probably had no path info or malformed URL
//Try to check it anyway
echo "No path to strip from $hostName" . PHP_EOL;
}
$wsArray = explode(".", $hostName); //Break it up into an array.
$wsHostName = "";
//Build domain one segment a time probably
//Code should be modified not to check for the first segment (.com)
while (!empty($wsArray)) {
$newSegment = array_pop($wsArray);
$wsHostName = $newSegment . $wsHostName;
echo "Checking $wsHostName" . PHP_EOL;
if (checkdnsrr($wsHostName, "A")) {
echo "host found $wsHostName" . PHP_EOL;
echo "Domain is $newSegment" . PHP_EOL;
continue(2);
} else {
//This segment didn't resolve - keep building
echo "No Valid A Record for $wsHostName" . PHP_EOL;
$wsHostName = "." . $wsHostName;
}
}
//if you get to here in the loop it could not resolve the host name
}
?>
try with preg_replace.
something like
$domain = preg_replace($regex, '$1', $url);
regex
function test($url)
{
// Check if the url begins with http:// www. or both
// If so, replace it
if (preg_match("/^(http:\/\/|www.)/i", $url))
{
$domain = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
}
else
{
$domain = $url;
}
// Now all thats left is the domain and the extension
// Only return the needed first part without the extension
$domain = explode(".", $domain);
return $domain[0];
}

PHP does not resolve .local dns names with gethostbyname

I have werid problem with name resolution. I am trying to connect to active directory server. I can successfully get the ldap server address from the SRV recodrs. Then I try to resolve the dns names to IP addresses and it fails:
<?php
echo 'example.com.:' . PHP_EOL;
echo gethostbyname('example.com.');
echo PHP_EOL;
echo 'dc1.veracomp.local.:' . PHP_EOL;
echo gethostbyname('dc1.my-company.local.');
echo PHP_EOL;
echo 'nslookup dc1.my-company.local.:' . PHP_EOL;
echo `nslookup dc1.my-company.local.`;
The example.com is resolved correctly, then the gethostbyname('dc1.my-company.local.') fails after a few seconds returning dc1.my-company.local. instead of the IP address. Still the same PHP script can call nslookup which correctly resolves the domain name...:
example.com.:
93.184.216.119
dc1.my-company.local.:
dc1.my-company.local.
nslookup dc1.my-company.local.:
Server: xxx.xxx.254.117
Address: xxx.xxx.254.117#53
Name: dc1.my-company.local
Address: 192.168.12.21
What is wrong here?
EDIT:
I am asking for name resolution beacuse the real problem i have is that I can connect to ldap://192.168.12.21 or to ldap://dc1.my-company.pl, but I cannot connect to ldap://dc1.my-company.local.
Unfortunatelly the SRV records for _ldap._tcp.my-company.pl returns only local addresses. I do not want to hardcode the .pl address. And I do not understand why I have to manually resolve the local addresses before passing them to Zend_Ldap as a host option.
You should avoid its use in production. DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.
I use this one; this will be faster and more efficient:
<?php
function getAddrByHost($hosts, $timeout = 3) {
$returnString = '';
foreach ($hosts as $host) {
$query = `nslookup -timeout=$timeout -retry=1 $host`;
if (preg_match('/\nAddress: (.*)\n/', $query, $matches))
$returnString .= trim($matches[1]) . '<br>';
$returnString .= $host . '<br>';
}
return $returnString;
}
$hostArray[] = 'www.example.com';
$hostArray[] = 'dc1.my-company.local';
$returnString = getAddrByHost($hostArray);
echo $returnString;
?>

php geo ip loc does not work

http://chir.ag/projects/geoiploc/
Hello, I am trying to set this up, but whenever I use include("geoiploc.php"); the page is blank and whenever I remove include("geoiploc.php"); I only see my IP address. I've uploaded geoiploc.php and index.php to a webhost that can run PHP.
If there is ANY other easier way to show country name by IP or any other way, which is it? Please I need this fast
So as I said, it only shows my IP whenever I remove include("geoiploc.php"); why?
You need this library: http://chir.ag/projects/geoiploc/autogen/geoiploc.tar.gz and this is the code to run the script:
include("geoiploc.php"); // Must include this
// ip must be of the form "192.168.1.100"
// you may load this from a database
$ip = $_SERVER["REMOTE_ADDR"];
echo "Your IP Address is: " . $ip . "<br />";
echo "Your Country is: ";
// returns country code by default
echo getCountryFromIP($ip);
echo "<br />\n";
// optionally, you can specify the return type
// type can be "code" (default), "abbr", "name"
echo "Your Country Code is: ";
echo getCountryFromIP($ip, "code");
echo "<br />\n";
// print country abbreviation - case insensitive
echo "Your Country Abbreviation is: ";
echo getCountryFromIP($ip, "AbBr");
echo "<br />\n";
// full name of country - spaces are trimmed
echo "Your Country Name is: ";
echo getCountryFromIP($ip, " NamE ");
echo "<br />\n";
You can use the free MaxMind Geo Lite. Download the files here: http://www.maxmind.com/download/geoip/api/php/php-latest.tar.gz
Then download the Geo Country database from here: http://dev.maxmind.com/geoip/legacy/geolite
You can now use it like this:
<?php
include("geoip.inc");
function ipAddress(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ // proxy pass ip
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$gi = geoip_open("path/to/GeoIP.dat",GEOIP_STANDARD);
echo geoip_country_name_by_addr($gi, ipAddress());
// echo geoip_country_code_by_addr($gi, ipAddress()); <-- country code
geoip_close($gi);
?>
UPDATE: to get the user's city you should download the top link and look for the file called sample_city.php to see some example code. You'll need to download this file: http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz and place it in the same directory as your php file. A quick example would be:
<?php
include("geoipcity.inc");
function ipAddress(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ // proxy pass ip
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$gi = geoip_open("GeoIPCity.dat",GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,ipAddress());
print $record->country_code . " " . $record->country_code3 . " " . $record->country_name . "\n";
geoip_close($gi);
?>

Categories