2017-02-28 7 views
0

2つのipv4アドレスを含む2つのphp変数があります。最初の3オクテットを比較し、一致すればtrue、 't。ブロックのコードを書くためのヘルプは高く評価されています。2つのphp変数に含まれる2つのIPアドレスの最初の3つのオクテットを比較する方法

<?php 
include('adodb/adodb.inc.php'); 
mysql_connect("173.86.45,9","abcd","1236"); 
mysql_select_db("vc"); 
$pl=mysql_query("SELECT stat_ip from Hasoffers"); 
$count=mysql_num_rows($pl); 


while($row=mysql_fetch_array($pl)) 
{ 
$stat_ip=$row['stat_ip']; 
echo sec($stat_ip)."<br>"; 
} 

function sec($stat_ip) 
{ 
    $result = mysql_query("select stat_ip from Hasoffers where stat_ip ='".$stat_ip."'"); 



        if(condition to check if the octets match) 
       { 
        //i need to write the condition if within the table Hasoffers, there are more than 2 'stat_ip'(column) values, having the same 3 octets. 
        printf("true"); 

        } 

       else 
       { 
       printf("false, octets don't match"); 


       } 
       return $num_rows; 
} 



?> 
+0

あなたがこれまでに試してみましたか? –

+0

show * 2つのipv4アドレスを含んでいる変数*簡単なヘルプを得るために – RomanPerekhrest

+0

@RomanPerekhrest私は統計情報の列(IPアドレスを含む)を含むテーブルHasoffersを持っています。重複したIPアドレスがある場合(最初の3オクテットのみを比較することによって)、同じ列内で見つける必要があります。 –

答えて

2

簡単な方法は次のとおりです。

$ip1 = '192.168.0.1'; 
$ip2 = '192.168.0.2'; 

$ip1 = explode('.', $ip1); 
$ip2 = explode('.', $ip2); 
if ($ip1[0]==$ip2[0] && $ip1[1]==$ip2[1] && $ip1[2]==$ip2[2]) { 
    //your code here 
} 

EDIT: 、この1(コメントを読む)を使用して秒()関数を置き換えるために試してみて、それを編集する。

function sec($stat_ip) 
{ 
$octets = explode('.', $stat_ip); 
$first_three = $octets[0].'.'.$octets[1].'.'.$octets[2].'.'; //this looks like 192.168.0. 
    $result = mysql_query("SELECT stat_ip from Hasoffers where stat_ip LIKE '".$first_three."%'"); //this gives you all ip's starting with the current ip 
    if (mysql_num_rows($result)>1) 
    { 
    //we have more than one ip starting with current ip 
    //do something here 
    } 
    else 
    { 
    //result returns 1 or 0 rows, no matching ip's 
    } 
    //return $something; 
} 
+0

上記のコードを参考にしてください。私は、Hasoffersという名前のテーブルのstat_ipという同じ列に含まれているip adrressの3オクテットを比較する必要があります。 –

+0

$ resultで取り込んだクエリは$ stat_ipで始まるipを返しますが、最初の3つのサブネットから始まる値だけを返す必要があります。これで$ first_threeがどこに使われていますか? ?これで私を助けてくれますか? –

+0

私の間違いはすみません。 stat_ipの代わりにクエリをfirst_threeにする必要があります、編集された答えを確認してください –

0

"。"を使用してexplodeを使用して配列に変換します。両方の配列の最初のインデックスを比較します。

1

使用このコード:これを実装する

$ipOne = "192.168.1.1"; 
    $ipTwo = "192.168.1.2"; 

    $ipOneParts = explode(".", $ipOne); 
    $ipTwoParts = explode(".", $ipTwo); 

    if(($ipOneParts[0] == $ipTwoParts[0]) && 
     ($ipOneParts[1] == $ipTwoParts[1]) && 
     ($ipOneParts[2] == $ipTwoParts[2])){ 
     return true; 
    } else { 
     return false; 
    } 
1

strrpossubstr機能を使用してソリューション:

$ip1 = '192.168.10.121'; 
$ip2 = '192.168.10.122'; 

// the position of the last octet separator 
$last_dot_pos = strrpos($ip1, '.'); 
$is_matched = substr($ip1, 0, $last_dot_pos) == substr($ip2, 0, $last_dot_pos); 

var_dump($is_matched); 

出力:

bool(true) 
関連する問題