How can I use an API to detect if an IP address is a VPN in PHP?

To detect if an IP address is a VPN using IP2Location.io in PHP, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed PHP and we won't cover that here. You will also need a paid subscription to the Security plan. Subscribe now!
  2. Save the below code into a file called test.php on your computer.
    PHP
    
    <?php
    $ch = curl_init();
    $ip = '8.8.8.8';
    $key = 'YOUR_API_KEY';
    curl_setopt($ch, CURLOPT_URL, 'https://api.ip2location.io/?' . http_build_query([
    	'ip' => $ip,
    	'key' => $key,
    	'format'  => 'json',
    ]));
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_errno > 0) {
    	echo 'ERROR: ' . $curl_error . PHP_EOL;
    }
    else {
    	$myobj = json_decode($response, true);
    	
    	if ($myobj !== null) {
    		if (isset($myobj['error'])) {
    			echo 'ERROR: ' . $myobj['error']['error_message'] . PHP_EOL;
    		}
    		else if (isset($myobj['proxy'])) {
    			if ($myobj['proxy']['is_vpn'] === true) {
    				echo 'The IP ' . $ip . ' is a VPN.' . PHP_EOL;
    			}
    			else {
    				echo 'The IP ' . $ip . ' is NOT a VPN.' . PHP_EOL;
    			}
    		}
    		else {
    			echo 'ERROR: The is_vpn field requires a paid subscription to the Security plan.' . PHP_EOL;
    		}
    	}
    	else {
    		echo 'ERROR: Invalid JSON in response.' . PHP_EOL;
    	}
    }
    			
  3. In the command line, run the below command.
    Bash
    
    php test.php
    			

This script will check if the specified IP address is a VPN. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free