To work with VPN connections and IP addresses in PHP, here are some key concepts and code examples:
Detecting User's IP Address (Including VPN Users)
function getUserIP() {
// Check for shared internet/ISP IP
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
// Check for IP from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
// Default remote address
else {
return $_SERVER['REMOTE_ADDR'];
}
}
$userIP = getUserIP();
echo "User IP: " . $userIP;
Checking if IP is from a VPN/Proxy (Using External Services)
function isVPNorProxy($ip) {
// Using ipinfo.io (requires API key)
$apiKey = 'YOUR_API_KEY';
$url = "https://ipinfo.io/{$ip}/json?token={$apiKey}";
$response = file_get_contents($url);
$data = json_decode($response, true);
return isset($data['privacy']) && ($data['privacy']['vpn'] || $data['privacy']['proxy']);
}
// Example usage
$ip = '123.45.67.89'; // Replace with actual IP
if (isVPNorProxy($ip)) {
echo "This IP is likely from a VPN or proxy";
} else {
echo "This IP appears to be direct";
}
Alternative VPN Detection Services
-
IP2Proxy (https://www.ip2location.com/database/ip2proxy)
// Requires their database or API
-
GetIPIntel (http://getipintel.net/)
$url = "http://check.getipintel.net/check.php?ip={$ip}&contact=your@email.com"; $result = file_get_contents($url); // Returns probability (0-1) of being VPN/proxy
Important Notes
- VPN detection isn't perfect - many legitimate users use VPNs for privacy
- Some VPN services rotate IP addresses frequently
- Consider your use case before blocking VPN users - it may negatively impact legitimate users
- For better accuracy, consider commercial IP intelligence services
Would you like more specific information about any particular aspect of PHP VPN/IP handling?
