2013-06-27 49 views
0

所以,编写这个脚本,现在我确实得到了正确的电子邮件,数据库中的旧IP地址以及脚本中的新地址。我现在的问题是,旧的IP地址和当前的电子邮件发送相同或不同。这个脚本会每分钟运行一次以检查动态ip地址的变化,所以我并不是每分钟都想要一封电子邮件。我的目标是只有当最后发布的IP与发现的IP不同时,才会发送电子邮件。现在,电子邮件发送给不同的IP。其他一切正常。这封电子邮件发送得很好,其他一切都完美无缺。唯一的问题是使用逻辑来决定何时发送电子邮件。 (当新的和旧的IP不同时)Php if else逻辑块无论运行什么?

当脚本从数据库中获得ip时,它看起来像123.123.123.123。来自http://www.ipaddresscheck.comlu.com/ip.php的IP也看起来像123.123.123.123。 (***示例)但是,如果数据库显示123.123.123.123,并且当前是134.134.134.134,则应发送电子邮件。

在比较中,我试过了!=,==,并且我试过把邮件块放在then和else部分。问题可能是由不同的数据类型引起的吗? $ new_ip是一个字符串,而$ old_ip是一个整数?我只有14岁,所以...是的。

<?php 
    //Get IP 
    $new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php'); 
    //Connect to SQL 
    mysql_connect('localhost','root','root'); 
    //Select database 
    mysql_select_db("ip_changes") or die(mysql_error()); 
    //Get Date Info 
    $date = date("D M Y"); 
    $time = date("H:i:s"); 
    //Get last inserted IP 
    $sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1'); 
    $row = mysql_fetch_array($sql); 
    $old_ip = $row['current_ip']; 
    echo $old_ip; 
    //Generate SQL query 
    $sql="INSERT INTO ip (date, time, current_ip) VALUES ('$date', '$time', '$new_ip')"; 
    //Execute SQL 
    mysql_query($sql); 
    //Get latest IP 
    //$lastip = mysql_query(SELECT $selected FROM ip ORDER BY id DESC LIMIT 1); 

    if ($old_ip == $current_ip) 
    { 

    } 

    else { 

    //Set Mail Settings 
    $to = "[email protected]"; 
    $subject = "IP Address Change"; 
    $from = "[email protected]://mar-remote-net.dns2.us"; 
    $headers = array (
    "From:" . $from, 
    "Content-Type: Text/HTML" 
    ); 
    //Create email 
    $finalmessage = <<< EOT 
    Hello! This is an automated message from the IPMS. An IP address change has been detected. 
    <html> 
    <style> 
    table, th, td 
    { 
    border: 2px solid black; 
    border-color:grey; 
    } 
    </style> 
    <table class='table'> 
    <tr> 
    <td>Old IP</td><td>New IP</td><td>Time Detected</td> 
    </tr> 
    <tr> 
    <td>$old_ip</td><td>$new_ip</td><td>$date $time</td> 
    </tr> 
    </table> 
    </html> 
    EOT; 
    mail($to,$subject,$finalmessage, implode("\r\n", $headers)); 
    mail('[email protected]', 'Hello!', implode("\r\n", $headers)); 


    } 
    ?> 
+0

var_dump($ old_ip)和var_dump($ current_ip)会告诉你在两种情况下你要处理的是哪种数据类型,但是,如果它们是从同一个源提取的,我看不出它有什么不同 – KyleK

+0

也许' $ new_ip'以换行符结束。尝试'$ new_ip = trim($ new_ip);' – Barmar

+0

你是否通过转换INET_ATON()来存储你的IP地址? – DevZer0

回答

1

你的意思是说$new_ip而不是$current_ipif声明?

$current_ip似乎没有在任何地方设置 - 如果是这种情况$current_ip将永远不会被设置,并且永远不会等于$old_ip

+0

对不起,当我说当前的IP我的意思是$ new_ip –

+0

我改变了第二个变种$ new_ip,但我仍然有同样的问题。没有echo $ old_ip,并且var_dump($ old_ip)var_dump($ new_ip)的输出是字符串(15)“123.123.123.123”string(167)“184.6.216.163”(123.123 ...是新的) –

+0

It看起来像我认为'$ old_ip'(值为184.6.216.163)的值用空格填充 - 一种解决方案是将条件更改为if(trim($ old_ip)== trim($ new_ip) )',但是你也可能想改变你存储IP地址的方式以避免填充(这意味着将数据库中的列类型改为例如'CHAR(15)')。 – CBerube