How to Check IP Address is Private or Public in PHP?

5430 views 1 year ago PHP

In this article, I will share with you How to find IP address was private or public in PHP with example. recently I was working on one payment portal and in this payment portal, I integrate many payment gateways. but in the payment integration, they only accept user public IP addresses not access private IP addresses. so, I search on google and find one solution. so, I will share it with you.

Syntax :

filter_var('ip_address', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE |  FILTER_FLAG_NO_RES_RANGE)

Example :

function ipCheck($ip_address)
{
    return filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE |  FILTER_FLAG_NO_RES_RANGE);
}
$checkPrivateIP = ipCheck('172.31.27.243');
if($checkPrivateIP == false) {
    echo 'Private IP';
} else {
    echo 'Public IP';
}

i hope you like this solution.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]