Skip to content

Instantly share code, notes, and snippets.

@wturnerharris
Last active October 18, 2016 21:36
Show Gist options
  • Save wturnerharris/b3aeea1b2fe1b22305523bacba546d26 to your computer and use it in GitHub Desktop.
Save wturnerharris/b3aeea1b2fe1b22305523bacba546d26 to your computer and use it in GitHub Desktop.
Restrict server access by whitelisting ip addresses - constructor accepts the request path
<?php
class IP_Access {
public $is_restricted = false;
private $protected_ips = array(
"..."
);
function __construct($request)
{
$this->is_restricted = ( in_array( $this->get_client_ip(), $this->protected_ips ) ) ? false : true;
$this->request_uri = $request;
if ( $this->is_restricted ) {
$this->throw_403_error();
}
}
function throw_403_error()
{
$title = "Access Denied";
header("HTTP/1.0 403 Forbidden");
$_die_code = sprintf(
'<html><head><title>%1$s</title><style type="text/css"></style></head><body><h1>%1$s</h1><p>The requested URL %2$s is inaccessible or not found on this server.</p><p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p><hr><address>Apache Server</address></body></html>',
$title,
$this->request_uri
);
die( $_die_code );
exit;
}
private function get_client_ip()
{
$_ip_addr = array(
'HTTP_X_PANTHEON_CLIENT_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
);
for ( $i = 0; $i < count( $_ip_addr ); $i++ )
{
$_ip = getenv( $_ip_addr[$i] );
if ( $this->is_reserved_ip( $_ip ) )
continue;
return $_ip;
}
return $_SERVER['REMOTE_ADDR'];
}
private function is_reserved_ip($ip)
{
$reserved_ips = array( // not an exhaustive list
'167772160' => 184549375, /* 10.0.0.0 - 10.255.255.255 */
'3232235520' => 3232301055, /* 192.168.0.0 - 192.168.255.255 */
'2130706432' => 2147483647, /* 127.0.0.0 - 127.255.255.255 */
'2851995648' => 2852061183, /* 169.254.0.0 - 169.254.255.255 */
'2886729728' => 2887778303, /* 172.16.0.0 - 172.31.255.255 */
'3758096384' => 4026531839, /* 224.0.0.0 - 239.255.255.255 */
);
$ip_long = sprintf('%u', ip2long($ip));
foreach ( $reserved_ips as $ip_start => $ip_end ) {
if ( ( $ip_long >= $ip_start ) && ( $ip_long <= $ip_end ) ) {
return TRUE;
}
}
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment