Posted By

mladoux on 09/21/10


Tagged

php apache security ban


Versions (?)

PHP/.htaccess Ban List 1.0


 / Published in: PHP
 

URL: http://mark.haktstudios.com/

Requires Apache, does not yet handle IP addresses with wildcards in them, that'll be in the next version

  1. <?php
  2.  
  3. /******************************************************************************
  4.   Configuration
  5. /******************************************************************************/
  6.  
  7. $admin_mail = 'admin@localhost'; // admin's email address
  8.  
  9. /******************************************************************************
  10.   Read Ban List from .htaccess ( so essentially, if they used a proxy and
  11.   apache misses it, the script can do a second check )
  12. /******************************************************************************/
  13. $banned_ip = array();
  14. $ban_list = file(PATH.'.htaccess');
  15.  
  16. foreach($ban_list as $line)
  17. {
  18. if (stripos($line, "deny from") !== false)
  19. {
  20. $line = trim($line);
  21. $parts = explode(' ', $line);
  22.  
  23. if ( stripos(trim($parts[2]), 'all') === false )
  24. {
  25. $banned_ip[] .= trim($parts[2]);
  26. }
  27. }
  28. }
  29.  
  30. /******************************************************************************
  31.   get_ip() - Attempts to retrieve the most accurate IP possible from user.
  32. /******************************************************************************/
  33.  
  34. function get_ip()
  35. {
  36. if(isset($_SERVER['X_FORWARDED_FOR']))
  37. {
  38. if(strpos($_SERVER['X_FORWARDED_FOR'], ',') === false)
  39. {
  40. return $_SERVER['X_FORWARDED_FOR'];
  41. }
  42. return trim(reset(explode(',', $_SERVER['X_FORWARDED_FOR'])));
  43. }
  44. return $_SERVER['REMOTE_ADDR'];
  45. }
  46.  
  47. $ip = get_ip();
  48.  
  49. if ( !is_empty($banned_ip) && in_array($ip, $banned_ip) )
  50. {
  51. header("HTTP/1.1 403 Forbidden");
  52. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  53. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  54. <html>
  55. <head>
  56. <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  57. <title>ERROR: 403 Forbidden - You have been banned!</title>
  58. <style type="text/css">
  59. </style>
  60. </head>
  61. <body>
  62. <h1>ERROR: 403 FORBIDDEN</h1>
  63. <p>
  64. It appears that your IP ( '.$ip.' ) has been banned from accessing
  65. this sites content. If you feel that this banning is in error, feel
  66. free to contact the sites administrator to have it removed.
  67. </p>
  68. <p>Admin Contact: <a href="MAILTO:'.$admin_mail.'">'.$admin_mail.'</a></p>
  69. </body>
  70. </html>
  71. ';
  72. die();
  73. }
  74.  
  75. // clean up variables
  76. unset($ip,$admin_mail,$banned_ip, $ban_list);
  77.  
  78. /* end of file */

Report this snippet  

You need to login to post a comment.