Grant access based on IP address with PHP

David Carr

Tutorials PHP & MySQL

Table of Contents

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.');
}

 

Fathom Analytics $10 discount on your first invoice using this link

Help support the blog so that I can continue creating new content!

Sponsor

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.