拒绝在PHP

时间:2017-08-29 18:59:43

标签: php security ip

我想拒绝使用无效IP地址的访问者访问我的门户网站。这是一个很好的解决方案吗?

   $ipaddress = '';
   if (getenv('HTTP_CLIENT_IP'))
       $ipaddress = getenv('HTTP_CLIENT_IP');
   else if(getenv('HTTP_X_FORWARDED_FOR'))
       $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
   else if(getenv('HTTP_X_FORWARDED'))
       $ipaddress = getenv('HTTP_X_FORWARDED');
   else if(getenv('HTTP_FORWARDED_FOR'))
       $ipaddress = getenv('HTTP_FORWARDED_FOR');
   else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
   else if(getenv('REMOTE_ADDR'))
       $ipaddress = getenv('REMOTE_ADDR');
   else
       $ipaddress = '';

   if ( filter_var ($ipaddress, FILTER_VALIDATE_IP) == false)
   {
      $ipaddress = '';
   }

   if ($ipaddress == '')
   {
      die ();
   }

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您只允许拥有真实IP地址的访问者不受欺骗?

下面的代码将允许您网站上的欺骗IP地址,但是,我修复了它并提供了一个非常短的功能 这将做你想要的。

<?php
$ipaddress = '';
   if (getenv('HTTP_CLIENT_IP'))
       $ipaddress = getenv('HTTP_CLIENT_IP');
   else if(getenv('HTTP_X_FORWARDED_FOR'))
       $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
   else if(getenv('HTTP_X_FORWARDED'))
       $ipaddress = getenv('HTTP_X_FORWARDED');
   else if(getenv('HTTP_FORWARDED_FOR'))
       $ipaddress = getenv('HTTP_FORWARDED_FOR');
   else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
   else if(getenv('REMOTE_ADDR'))
       $ipaddress = getenv('REMOTE_ADDR');
   else
       $ipaddress = '';

   if ( filter_var ($ipaddress, FILTER_VALIDATE_IP) == false)
   {
      $ipaddress = '';
      die();
   }

   /**  You don't want this here;
        kill the script once IP Validation return false.
   if ($ipaddress == '')
   {
      die ();
   }
   */

##使用以下功能;

   function checkIPAddress()
   {
      // Get IP Address using $_SERVER['REMOTE_ADDR'];
      $ipaddress = ($_SERVER('REMOTE_ADDR')) ? $_SERVER('REMOTE_ADDR') : '';

       if ( filter_var ($ipaddress, FILTER_VALIDATE_IP) == false)
       {
          $ipaddress = '';
          die();
       }
   }
允许HTTP_X_FORWARDED是一个坏习惯。在进行代理服务器,负载平衡等时使用它。