Skip to content

Instantly share code, notes, and snippets.

@hctilg
Created July 30, 2024 18:55
Show Gist options
  • Save hctilg/9972b3f139e3baf88ae68c1a97945772 to your computer and use it in GitHub Desktop.
Save hctilg/9972b3f139e3baf88ae68c1a97945772 to your computer and use it in GitHub Desktop.
Get real ip address
<?php
function real_ip() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
// Check IP from internet shared proxy
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Check IP from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
// Get IP from remote address
$ip = $_SERVER['REMOTE_ADDR'];
} else {
// Suppose IP is localhost
$ip = '127.0.0.1';
}
// If IP is an IPv6 address, extract the IPv4 address from it
if (strpos($ip, '::') !== false) $ip = substr($ip, 0, strpos($ip, '::'));
if (empty(trim($ip))) $ip = '127.0.0.1';
return $ip;
}
// Example usage:
$ip = real_ip();
echo "Your real IP address is: $ip";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment