PHP & MySQL | Tutorials

David Carr

Grant access based on IP address with PHP

A quick tip for only allowing access to a website for a range of IP addresses. 

This is a very simply and useful way of allowing access to only certain IP addresses maybe you have a web application that you only want to be accessed from a certain location, then this solution is perfect for that task.

First create an array of IP addresses that you want to allow, make sure the last item does not have a ending comma.

$allowlist = array(
    '36.285.23.23',
    '12.101.67.56',
    '98.465.23.89',
    '16.289.90.10',
    '71.214.228.18'
);

Next check if the users IP address is in the allowed list, if its not stop the script and print a message using the die command.

The users IP address can be accessed from a global function called $_SERVER['REMOTE_ADDR'].

To check use a function called in_array that expect 2 parameters the first is the item to look for and the section is the array, this returns true if there is a march so using the not operator ! before using in_array says if its not in the array

if(!in_array($_SERVER['REMOTE_ADDR'],$allowlist)){
    die('This website cannot be accessed from your location.');
}

Putting it all together:

//collection of allowed IP addresses
$allowlist = array(
    '36.285.23.23',
    '12.101.67.56',
    '98.465.23.89',
    '16.289.90.10',
    '71.214.228.18'
);

//if users IP is not in allowed list kill the script
if(!in_array($_SERVER['REMOTE_ADDR'],$allowlist)){
    die('This website cannot be accessed from your location.');
}

 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.