Display the Content only to the allowed IP address in 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 of all create an array of IP addresses that you want to allow, make sure the last item does not have a ending comma.

Next check if the Your IP address is in the allowed list, if its not stop the script and print a message using the die command. an you will not view your page content,

creat IP List, if you can use just 1 IP then use this

//allowed IP address
$allowlist = array(
‘123.23.45.67’
);

if you want to use more IP in List the use

//collection of allowed IP addresses
$allowlist = array(
‘123.23.45.67’,
‘123.24.46.78’,
‘123.235.43.674’,
);

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

now this is full code, you can copy and paste just edit your IP address and add on the top of your page, header, or config

<?php
//collection of allowed IP addresses
$allowlist = array(
‘123.23.45.67’,
‘123.24.46.78’,
‘123.235.43.674’,
);

localeconv($allowcity);

//if users IP is not in allowed list kill the script
if(!in_array($_SERVER[‘REMOTE_ADDR’],$allowlist,$allowcity))
{
die(‘Sorry ! you are not allow to accessed this page.’);
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *