Link to home
Start Free TrialLog in
Avatar of air4casts
air4casts

asked on

PHP/MySQL Control Page Access with IP Address

PHP script to compare IP address with Ip addresses stored in MySQL file and redirect.

Obviously works fine when retrieved value and mysql store values are both 86.131.178.77, for example.

How do we match a retrieved value of 86.131.178.77 with a stored value of 86.131.178?
In a simpler script without mysql preg_match does it.
Avatar of Cornelia Yoder
Cornelia Yoder
Flag of United States of America image

SELECT * FROM Table WHERE SUBSTRING_INDEX(IPAddress,'.',3) = '86.131.178'

Avatar of hielo
>>86.131.178.77 with a stored value of 86.131.178?
It looks like you are interested in matching subnets. Since the IPs are delimited by a period, you can just
do:
$dbquad = explode(".",$dbip);
$retrievedquad = explode(".",$retrievedip);

Then compare the individual quad values or "clear" the last quad and join them again for comparison:
$dbquad[3] = 0;
$retrievedquad[3]=0;
$dbquad = implode(".",$dbquad)
$retrievedquad = implode(".",$retrievedquad);
if($retrievedquad == $dbquad)
{
 echo("matching subnet");
}
Avatar of air4casts
air4casts

ASKER

Thank you for your speedy reply. Understand it but would welcome a moment further; need to incrporate into the simplest of recordsets where $ip is 'REMOTE_ADDR'. Recordset is:

mysql_select_db($database_conn_333mysql, $conn_333mysql);
$query_rst_consult = "SELECT * FROM consultcomp WHERE cons_ipad = '$ip'";
$rst_consult = mysql_query($query_rst_consult, $conn_333mysql) or die(mysql_error());
$row_rst_consult = mysql_fetch_assoc($rst_consult);
$totalRows_rst_consult = mysql_num_rows($rst_consult);
$zzz=$totalRows_rst_consult;
$idred=$row_rst_consult['cons_redirid'];
mysql_free_result($rst_consult);
if($zzz==1){

Could you help further?
"SELECT * FROM consultcomp WHERE SUBSTRING_INDEX(cons_ipad,'.',3) = SUBSTRING_INDEX(" . $ip . ",'.',3)";
A complication arises when people are entering ip addresses in different formats sometimes omitting the last three digits, sometimes omitting only one. Are we obliged to ask them to conform to a template?
ASKER CERTIFIED SOLUTION
Avatar of Cornelia Yoder
Cornelia Yoder
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SELECT * FROM consultcomp WHERE
SUBSTRING(cons_ipad FROM 1 FOR LEAST(LENGTH(cons_ipad),LENGTH('$ip')))
=
SUBSTRING('$ip' FROM 1 FOR LEAST(LENGTH(cons_ipad),LENGTH('$ip')))

will compare the two strings to the length of the shorter one.