Calculate IP Between IP range PHP - php

How do i calculate between Ip Addresses.
for Example:
$ip_low_range = '91.0.0.0';
$ip_max_range = '91.23.255.255';
$user_ip = '91.1.0.0';
in_range($user_ip , $ip_low_range , $ip_max_range,);
in_range() - is the function that i'm looking for.
Thanks!

You could use ip2long:
$ip_low_range = ip2long('91.0.0.0');
$ip_max_range = ip2long('91.23.255.255');
$user_ip = ip2long('91.1.0.0');
if ($user_ip >= $ip_low_range && $user_ip <= $ip_max_range) {
echo "in range";
}

Related

Show different time when at different country

Want to ask.
How do I create a website that is able to show different time when at different country.
Example:
If user is using the website at Japan, it will show Japan's time.
While If user is using the website at Britain, it will show Britain's time.
Right now I am using this code:
<?php
date_default_timezone_set("Asia/Tokyo");
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
You should do it on the client-side. I have read a forum once and they recommended it to be done in the client per se. Take what you think might help you from this javascript code example:
var now = new Date();
var utcString = now.toISOString().substring(0, 19);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var localDatetime = year + "-" +
(month < 10 ? "0" + month.toString() : month) + "-" +
(day < 10 ? "0" + day.toString() : day) + "T" +
(hour < 10 ? "0" + hour.toString() : hour) + ":" +
(minute < 10 ? "0" + minute.toString() : minute) +
utcString.substring(16, 19);
//var datetimeField = document.getElementById("myDatetimeField");
//datetimeField.value = localDatetime;
alert(localDatetime);
There is no function in php that can get user based timezone. But there is way around. First you have to grab user IP address, then you have make a call to a third party service to get geo information. Thus you can get user timezone.
The following function is fool-proof solution to get user IP using php so far. And credits goes to https://stackoverflow.com/a/38852532/7935051
<?php
function getClientIp() {
$ipAddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ipAddress = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ipAddress = $_SERVER['HTTP_X_FORWARDED'];
} elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_FORWARDED'])) {
$ipAddress = $_SERVER['HTTP_FORWARDED'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ipAddress = $_SERVER['REMOTE_ADDR'];
} elseif (getenv('REMOTE_ADDR')) {
$ipAddress = getenv('REMOTE_ADDR');
} else {
$ipAddress = 'Unknown';
}
return $ipAddress;
}
Now you have to depend on the third party services to get geo information. This is very true for this type of jobs. There are several free services on internet, for example, geoPlugin. You may use it. See more details.
// Gets the client IP
$userIp = getClientIp();
$geoInfo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip={$userIp}"));
// Gets the timezone
$timezone = $geoInfo['geoplugin_timezone'];
// Sets user timezone, otherwise uses default
if ($timezone) {
date_default_timezone_set($timezone);
} else {
date_default_timezone_set('Asia/Tokyo');
}
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
BTW you may debug $geoInfo variables to get more information

Build if statement from variable string

I am wanting to create an if(){} statement from the information specified in a variable.
My current code creates the string from a foreach loop, I am trying to filter out IP addresses in my code from being entered into my database.
Code that creates the string:
//Set excluded IP's
$exclude = "10.1.1.0/24, 192.168.1.0/24";
//Convert excluded to ranges
$ranges = cidrToRange($exclude);
//Build IP address exclusion if statement
$statement = NULL;
foreach($ranges as $ip_ranges) {
$statement .= " !((".ip2long($ip_ranges['start'])." <= $ip_address) && ($ip_dst <= ".ip2long($ip_ranges['end']).")) AND ";
}
//Strip and at end
$statement = rtrim($statement, "AND ");
The $ip_address variable needs to be inserted into the if statement afterwards(later in the script)
The $statement output of this code with the values specified in the $exclude variable will output:
!((167837952 <= $ip_address) && ($ip_address <= 167838207)) AND !((3232235776 <= $ip_address) && ($ip_address <= 3232236031))
I am wanting to use that string in an if statement, so the final result should look like:
if(!((167837952 <= $ip_address) && ($ip_address <= 167838207)) AND !((3232235776 <= $ip_address) && ($ip_address <= 3232236031))) {
//Do this
}
Is this possible to implement into my code?
Building a dynamic if statement is one thing, testing it is another. A simple alternative is to just search through the list and check if the IP address falls into the range. This checks each item and as soon as it matches it will stop and $save will be false.
//Convert excluded to ranges
$ranges = cidrToRange($exclude);
// Check if IP is to be saved -
$save = true;
foreach ( $ranges as $ip_ranges) {
if ( $ip_ranges['start'] <= $ip_address && $ip_address <= $ip_ranges['end'] ) {
$save = false;
break;
}
}
This assumes that $ip_address is also a long and not a string, something like...
$ip_address = ip2long("10.10.0.1");
I have figured out a way to do what I was wanting
My code
//Check if IP address is in a range
function check_ip_range($ip_address, $ip_ranges){
$ip_address = ip2long($ip_address);
foreach($ip_ranges as $ranges) {
if((ip2long($ranges['start']) <= $ip_address && $ip_address <= ip2long($ranges['end']))) {
//echo long2ip($ip_address)." is between ".$ranges['start']." and ".$ranges['end']."<br>";
return(true);
}
}
return(false);
}
I now have my code in my script like this:
//Configure ranges to exclude from accounting
$config['accounting']['exclude'] = "10.0.0.0/8";
//Convert ranges to array start and end
$exclude_ranges = cidrToRange($config['accounting']['exclude']);
//If IP is not in range
if(!check_ip_range($ip_address, $exclude_ranges)) {
//Do this
}

Splitting an IP Address Range, IP addresses stop after 210937 records

I have a database of IP ranges and I am using the code below to split the range in to individual IP addresses. This works fine until I get to 210937 records then the code stops spilitting the IP range and starts inserting 0.0.0.0.
I have tried removing some IP addresses but it still stops at the same point even though the IP address is different.
for ($ip = ip2long($ip1); $ip<=ip2long($ip2); $ip++)
{
$lip = long2ip($ip);
Any suggestions would be appreciated.
Ok so here is the full code minus db connection.
$query1 = "SELECT * FROM masteriplist";
$result = mysql_query($query1);
while($row = mysql_fetch_array($result))
{
$ipe = $row['ip_end_range'];
$ips = $row['ip_start_range'];
$ip1 = "$ips";
$ip2 = "$ipe";
for ($ip = ip2long($ip1); $ip<=ip2long($ip2); $ip++)
{
$lip = long2ip($ip);
mysql_query("INSERT INTO ip_master (ip) VALUES ('$lip')")
or die(mysql_error());
}
}
ok the debugging code returned the following
array(24) {
["id"]=> string(2) "50"
["ip_address"]=> string(12) "85.119.25.27"
["ip_start_range"]=> string(0) ""
["ip_end_range"]=> string(0) ""
...
}
It looks like you're processing a single IP address instead of a range; dealing with both could be done with this:
if ($row['ip_start_range'] == '' || $row['ip_end_range'] == '') {
$ip1 = $ip2 = $row['ip_address'];
} else {
$ip1 = $row['ip_start_range'];
$ip2 = $row['ip_end_range'];
}
Also, you could make it more efficient by moving the ip2long calls outside of the loop:
$start = ip2long($ip1);
$stop = ip2long($ip2);
for ($ip = $start; $ip <= $stop; $ip++) {
// ...
}

How to compare a range of local ip addresses to a public ip address in php?

How can I compare a range of local ip address to public ip address in php?
I would like to compare my IP adddress in Range or not.
If it isn't in range, I want to echo "fail connected"?
$ipRanges = array(
array( '10.1.1.1' , '10.1.10.255' ) ,
array( '192.168.12.1' , '192.168.12.16' )
);
$theIP = '10.1.5.5'; # Could be $_SERVER['REMOTE_ADDR'] for accessing IP address
$theIPdec = ip2long( $theIP ); # Converts from an IP address to an integer
$inRange = false;
foreach( $ipRanges as $r ){
if( $theIPdec >= ip2long( $r[0] )
&& $theIPdec <= ip2long( $r[1] ) ){
# IP is in this range
$inRange = true;
break;
}
}
if( !$inRange ){
# No Matches to Ranges
echo 'fail connected';
}

how to restrict a page to only a specified ip range in php

im looking for a way to restrict my administration page to only my own ip range
concider my ip range is 215.67..
so in php i will begin with this :
$myip = "215.67.*.*";
$myip = explode(".", $my_ip);
$userip = getenv("REMOTE_ADDR") ;
$userip = explode(".", $userip);
if ($myip[0] == $userip[0] AND $myip[1] == $userip[1] ) {
//Contunue admin
}
is there any better and more professional way to do it ?
<?php
function in_ip_range($ip_one, $ip_two=false){
if($ip_two===false){
if($ip_one==$_SERVER['REMOTE_ADDR']){
$ip=true;
}else{
$ip=false;
}
}else{
if(ip2long($ip_one)<=ip2long($_SERVER['REMOTE_ADDR']) && ip2long($ip_two)>=ip2long($_SERVER['REMOTE_ADDR'])){
$ip=true;
}else{
$ip=false;
}
}
return $ip;
}
//usage
echo in_ip_range('192.168.0.0','192.168.1.254');
?>
Taken from http://www.php.net/manual/en/function.ip2long.php#81030

Categories