-- 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_FORWARDED_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.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
The issue says unexpected {..... I dont understand why this is hapenning i remove it and i still ahve issues. Please reply with th right code.
Kevin Andrews / Auth
<?php
$shortenedlink = mt_rand(10000,99999);
$longlink = $_POST['longlink'];
if(!isset($longlink) || trim($longlink) == '')
{
echo "The link field is empty. Redirecting you in 3 seconds.";
header ( "refresh:3;url=http://auth.kenygamer.com" );
exit;
$shortenedlinkpath = "$shortenedlink.asp";
if (file_exists($shortenedlinkpath))
{
echo "An error occurred creating the shortened link, because the assigned number already exists. However, you can retry. Copy the link and paste it again on the main page:<br><br>$longlink<br><br>Redirecting you in 15 seconds.";
header( "refresh:15;url=http://auth.kenygamer.com" );
exit;
}
else
{
echo "";
}
$shortenedfilecontent = '<title>Outgoing link</title><meta http-equiv="refresh" content="5; url=$longlink">';
$fp = fopen("$shortenedlink.asp", "w");
fwrite($fp, $shortenedfilecontent).' ';
fclose($fp);
echo ("The shortened URL has been successfully created. The shortened number #$shortenedlink has been assigned to your long URL $longlink. Therefore, it is accessible at https://auth.kenygamer.com/$shortenedlink at any time. Remember that you can always create new shortened URLs.<br><br>Long link: $longlink<br>Shortened link: $shortenedlink<br><br>Redirecting you in 20 seconds.");
header( "refresh:20;url=https://auth.kenygamer.com/$shortenedlink" );
?>
You forgot to add the } after the exit;
This should help you:
<?php
$shortenedlink = mt_rand(10000, 99999);
$longlink = $_POST['longlink'];
if (!isset($longlink) || trim($longlink) == '') {
echo "The link field is empty. Redirecting you in 3 seconds.";
header("refresh:3;url=http://auth.kenygamer.com");
exit;
}
$shortenedlinkpath = "$shortenedlink.asp";
if (file_exists($shortenedlinkpath)) {
echo "An error occurred creating the shortened link, because the assigned number already exists. However, you can retry. Copy the link and paste it again on the main page:<br><br>$longlink<br><br>Redirecting you in 15 seconds.";
header("refresh:15;url=http://auth.kenygamer.com");
exit;
} else {
echo "";
}
$shortenedfilecontent = '<title>Outgoing link</title><meta http-equiv="refresh" content="5; url=$longlink">';
$fp = fopen("$shortenedlink.asp", "w");
fwrite($fp, $shortenedfilecontent) . ' ';
fclose($fp);
echo ("The shortened URL has been successfully created. The shortened number #$shortenedlink has been assigned to your long URL $longlink. Therefore, it is accessible at https://auth.kenygamer.com/$shortenedlink at any time. Remember that you can always create new shortened URLs.<br><br>Long link: $longlink<br>Shortened link: $shortenedlink<br><br>Redirecting you in 20 seconds.");
header("refresh:20;url=https://auth.kenygamer.com/$shortenedlink");
?>
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;
?>
I'm wondering if it possible to create network layer packets (i.e. define my own IP headers) using PHP? It seems like socket_create with SOCK_RAW only lets you define the contents of the IP packet, not the headers itself.
Thanks in advance for your replies!
I was able to successfully create a socket using SOCK_RAW on Mac OS X, as long as I ran the script as root.
The example I used was taken from Jean Charles MAMMANA's ping.inc.php
I created a ping.php wrapper, and executed: sudo ping.php www.google.com.
Here's my ping.php wrapper:
<?php
$default_timeout = 15;
require("ping.inc.php");
if (count($argv) < 2) usage();
$timeout = count($argv) >= 3 ? intval($argv[2]) : $default_timeout;
$host = $argv[1];
$result = ping($host, $timeout);
if ($result < 0) {
echo "Error: " . $g_icmp_error . "\n";
} else {
echo "$result ms\n";
}
function usage() {
global $argv;
echo "Usage: {$argv[0]} <host> [timeout]\n";
die();
}
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;