Is there a function in PHP from which we can detect the type of IP?

Viewed 47

I have a web application which takes the IP. I want to know if we can use a function to detect the type of IP in PHP (IPv4 or IPv6)?

I know we can get the IP in PHP by using this:

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

This gives the IP address but I can't find the variable which gives what type of IP it got (IPv4, IPv6).

Any help or leads?

1 Answers

You can verify what type of IP address it is by using filter_var

For example

filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); // true
filter_var('::1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); // true

Don't forget that HTTP_X_FORWARDED_FOR (or any other _X_ header) can be spoofed easily.

Related