Skip to main content
TopMiniSite

Back to all posts

How to Get A Client Real IP Address In PHP?

Published on
11 min read
How to Get A Client Real IP Address In PHP? image

Best Tools to Buy for IP Tracking in PHP in January 2026

1 REOLINK PTZ Security Camera System 4K, IP PoE 360 Camera with Dual-Lens, Auto 6X Hybrid Zoomed Tracking, 355 Pan & 90 Tilt, Outdoor Surveillance, AI Detection, TrackMix PoE

REOLINK PTZ Security Camera System 4K, IP PoE 360 Camera with Dual-Lens, Auto 6X Hybrid Zoomed Tracking, 355 Pan & 90 Tilt, Outdoor Surveillance, AI Detection, TrackMix PoE

  • DUAL VIEW: TELEPHOTO AND WIDE-ANGLE LENSES FOR TOTAL COVERAGE.

  • SMART DETECTION & PLAYBACK: TRACK MOVEMENTS, REPLAY CLIPS EASILY.

  • INSTANT ALERTS: GET NOTIFIED OF SUSPICIOUS ACTIVITY RIGHT AWAY.

BUY & SAVE
$189.99
REOLINK PTZ Security Camera System 4K, IP PoE 360 Camera with Dual-Lens, Auto 6X Hybrid Zoomed Tracking, 355 Pan & 90 Tilt, Outdoor Surveillance, AI Detection, TrackMix PoE
2 EVERSECU 7 Inch Touch Screen 5 in 1 CCTV Tester with Cable Tracer, Support Upt to 4K IP Camera & 8.0 Megapixel AHD, TVI, CVI & CVBS Analog Camera, with Keyboard/IP Discovery/POE Output/APP

EVERSECU 7 Inch Touch Screen 5 in 1 CCTV Tester with Cable Tracer, Support Upt to 4K IP Camera & 8.0 Megapixel AHD, TVI, CVI & CVBS Analog Camera, with Keyboard/IP Discovery/POE Output/APP

  • 7-INCH IPS TOUCH SCREEN FOR EASY NAVIGATION AND REAL-TIME TESTING.
  • COMPREHENSIVE COMPATIBILITY WITH MULTIPLE CAMERA FORMATS AND BRANDS.
  • ROBUST NETWORK TOOLS FOR EFFICIENT IP DETECTION AND TROUBLESHOOTING.
BUY & SAVE
$395.99
EVERSECU 7 Inch Touch Screen 5 in 1 CCTV Tester with Cable Tracer, Support Upt to 4K IP Camera & 8.0 Megapixel AHD, TVI, CVI & CVBS Analog Camera, with Keyboard/IP Discovery/POE Output/APP
3 Tapo TP-Link 2K Pan/Tilt Indoor Security Camera for Baby Monitor, Pet Camera, Motion Detection & Tracking, 2-Way Audio, Cloud & SD Card Storage, Works w/Alexa & Google Home, Black, C211(2-Pack)

Tapo TP-Link 2K Pan/Tilt Indoor Security Camera for Baby Monitor, Pet Camera, Motion Detection & Tracking, 2-Way Audio, Cloud & SD Card Storage, Works w/Alexa & Google Home, Black, C211(2-Pack)

  • CAPTURE EVERY DETAIL IN CRYSTAL-CLEAR 2K HD FOR PEACE OF MIND.

  • 360° PANORAMIC VIEW ENSURES NO BLIND SPOTS IN YOUR HOME.

  • INSTANT ALERTS FOR MOTION & CRYING; STAY INFORMED, WORRY-FREE!

BUY & SAVE
$36.98 $43.99
Save 16%
Tapo TP-Link 2K Pan/Tilt Indoor Security Camera for Baby Monitor, Pet Camera, Motion Detection & Tracking, 2-Way Audio, Cloud & SD Card Storage, Works w/Alexa & Google Home, Black, C211(2-Pack)
4 Tapo 2K Pan/Tilt Indoor Security Camera for Baby Monitor, Pet Camera | Motion Detection & Tracking | 2-Way Audio | Cloud & SD Card Storage | Works w/Alexa & Google Assistant | Black C211

Tapo 2K Pan/Tilt Indoor Security Camera for Baby Monitor, Pet Camera | Motion Detection & Tracking | 2-Way Audio | Cloud & SD Card Storage | Works w/Alexa & Google Assistant | Black C211

  • CRYSTAL-CLEAR 2K VIDEO: EXPERIENCE EVERY DETAIL WITH STUNNING CLARITY.

  • 360° PAN/TILT VIEW: COVERS EVERY ANGLE OF YOUR HOME EFFORTLESSLY.

  • SMART DETECTION ALERTS: GET INSTANT NOTIFICATIONS FOR IMPORTANT EVENTS.

BUY & SAVE
$19.97 $23.99
Save 17%
Tapo 2K Pan/Tilt Indoor Security Camera for Baby Monitor, Pet Camera | Motion Detection & Tracking | 2-Way Audio | Cloud & SD Card Storage | Works w/Alexa & Google Assistant | Black C211
5 TONGVEO 4K NDI PTZ Camera AI Auto-Tracking 20X Optical Zoom HDMI IP Live Streaming SDI USB3.0 PoE LAN Supports for Church Worship Event Video Conference YouTube OBS vMix Zoom Teams and More

TONGVEO 4K NDI PTZ Camera AI Auto-Tracking 20X Optical Zoom HDMI IP Live Streaming SDI USB3.0 PoE LAN Supports for Church Worship Event Video Conference YouTube OBS vMix Zoom Teams and More

  • ELEVATE PRODUCTION QUALITY WITH STUNNING 4K STREAMING CAPABILITIES.
  • EFFORTLESS SETUP WITH OFFICIAL NDI INTEGRATION FOR SEAMLESS STREAMING.
  • ADVANCED AI AUTO-TRACKING KEEPS SUBJECTS PERFECTLY FRAMED EVERY TIME.
BUY & SAVE
$459.00
TONGVEO 4K NDI PTZ Camera AI Auto-Tracking 20X Optical Zoom HDMI IP Live Streaming SDI USB3.0 PoE LAN Supports for Church Worship Event Video Conference YouTube OBS vMix Zoom Teams and More
6 REOLINK Smart 5MP 8CH Home Security Camera System, 4pcs Wired PoE IP Cameras Outdoor with Person/Pet/Vehicle Detection, 4K 8CH NVR with 2TB HDD for 24-7 Recording, RLK8-520D4-5MP

REOLINK Smart 5MP 8CH Home Security Camera System, 4pcs Wired PoE IP Cameras Outdoor with Person/Pet/Vehicle Detection, 4K 8CH NVR with 2TB HDD for 24-7 Recording, RLK8-520D4-5MP

  • NIGHT VISION UP TO 100FT: PROTECT YOUR PROPERTY WITH CLEAR 5MP HD FOOTAGE EVEN IN DARKNESS.

  • SMART DETECTION TECHNOLOGY: MINIMIZE FALSE ALERTS BY IDENTIFYING PEOPLE, ANIMALS, AND VEHICLES.

  • EASY PLUG & PLAY SETUP: INSTALL YOUR SECURITY SYSTEM EFFORTLESSLY WITHOUT PROFESSIONAL HELP.

BUY & SAVE
$319.99 $439.99
Save 27%
REOLINK Smart 5MP 8CH Home Security Camera System, 4pcs Wired PoE IP Cameras Outdoor with Person/Pet/Vehicle Detection, 4K 8CH NVR with 2TB HDD for 24-7 Recording, RLK8-520D4-5MP
7 Rsrteng IPC-9800MOVTADHS Pro Full Features CCTV Camera Tester 8K 32MP IP Camera Tester wtih POE++ Max 90W, CCTV Tester with 4K TVI CVI AHD SDI Support DMM OPM VFL TDR 1CH SFP HD VGA WIFI Network Tools

Rsrteng IPC-9800MOVTADHS Pro Full Features CCTV Camera Tester 8K 32MP IP Camera Tester wtih POE++ Max 90W, CCTV Tester with 4K TVI CVI AHD SDI Support DMM OPM VFL TDR 1CH SFP HD VGA WIFI Network Tools

  • 8K VIDEO TESTING: TEST AND MONITOR CAMERAS UP TO 8K RESOLUTION SEAMLESSLY.
  • VERSATILE CABLE TRACER: QUICKLY IDENTIFY CABLES WITH BUILT-IN TRACING TOOLS.
  • COMPREHENSIVE NETWORK TOOLS: INCLUDES DHCP, PING, AND LINK MONITORING FEATURES.
BUY & SAVE
$649.99
Rsrteng IPC-9800MOVTADHS Pro Full Features CCTV Camera Tester 8K 32MP IP Camera Tester wtih POE++ Max 90W, CCTV Tester with 4K TVI CVI AHD SDI Support DMM OPM VFL TDR 1CH SFP HD VGA WIFI Network Tools
8 Anpviz 6MP PoE PTZ Camera Outdoor, 5X Optical Zoom 2.7~13.5mm Lens, Pan Tilt Zoom IP Security Camera with Human Vehicle Detection, Spotlight&Sound Alarm, SD Card Slot, IP66, NDAA Compliant (U Series)

Anpviz 6MP PoE PTZ Camera Outdoor, 5X Optical Zoom 2.7~13.5mm Lens, Pan Tilt Zoom IP Security Camera with Human Vehicle Detection, Spotlight&Sound Alarm, SD Card Slot, IP66, NDAA Compliant (U Series)

  • HD VIDEO & EASY INSTALLATION: 25FPS AT 6MP FOR SMOOTH, VIVID IMAGES.

  • WIDE COVERAGE & DURABILITY: 280° PAN AND IP66 WEATHERPROOF FOR ALL SETUPS.

  • SMART DETECTION ALERTS: MINIMIZED FALSE ALARMS WITH CUSTOMIZABLE NOTIFICATIONS.

BUY & SAVE
$94.98 $99.98
Save 5%
Anpviz 6MP PoE PTZ Camera Outdoor, 5X Optical Zoom 2.7~13.5mm Lens, Pan Tilt Zoom IP Security Camera with Human Vehicle Detection, Spotlight&Sound Alarm, SD Card Slot, IP66, NDAA Compliant (U Series)
9 ZOSI C290 4K 8MP UHD Wired WiFi Security Camera Outdoor Indoor, Plug-in Pan/Tilt IP Camera, AI Human Face Vehicle Detection, Auto Tracking, Night Vision, Siren Alarm, 2-Way Audio, 64GB Memory Card

ZOSI C290 4K 8MP UHD Wired WiFi Security Camera Outdoor Indoor, Plug-in Pan/Tilt IP Camera, AI Human Face Vehicle Detection, Auto Tracking, Night Vision, Siren Alarm, 2-Way Audio, 64GB Memory Card

  • 4K ULTRA HD WITH 360° COVERAGE FOR EVERY DETAIL CAPTURE EVERY MOMENT WITH STUNNING 4K VIDEO AND FULL AREA COVERAGE.

  • SMART AI DETECTION & INSTANT ALERTS FOR ENHANCED SECURITY RECEIVE REAL-TIME NOTIFICATIONS AND TRACK MOVEMENT WITH ADVANCED AI.

  • WEATHERPROOF DESIGN WITH CLEAR NIGHT VISION UP TO 100FT BUILT TO WITHSTAND ELEMENTS WHILE ENSURING VISIBILITY IN THE DARK.

BUY & SAVE
$69.99
ZOSI C290 4K 8MP UHD Wired WiFi Security Camera Outdoor Indoor, Plug-in Pan/Tilt IP Camera, AI Human Face Vehicle Detection, Auto Tracking, Night Vision, Siren Alarm, 2-Way Audio, 64GB Memory Card
10 Amcrest 1080P WiFi Camera Indoor, Nanny Cam, Dog Camera, Sound & Baby Monitor, Human & Pet Detection, Motion-Tracking, 2.4Ghz Only, Pan/Tilt Wireless IP Camera, Night Vision, Smart Home ASH21-B

Amcrest 1080P WiFi Camera Indoor, Nanny Cam, Dog Camera, Sound & Baby Monitor, Human & Pet Detection, Motion-Tracking, 2.4Ghz Only, Pan/Tilt Wireless IP Camera, Night Vision, Smart Home ASH21-B

  • AI-POWERED HUMAN DETECTION: NO CLOUD RELIANCE, ENSURING PRIVACY AND RELIABILITY.

  • MULTI-FUNCTION BABY MONITOR: ADJUSTABLE SOUND ALERTS FOR PEACE OF MIND.

  • SEAMLESS 1080P STREAMING: LIVE FEED WITH PTZ CONTROL AND WIDE 93° VIEW.

BUY & SAVE
$19.99 $29.99
Save 33%
Amcrest 1080P WiFi Camera Indoor, Nanny Cam, Dog Camera, Sound & Baby Monitor, Human & Pet Detection, Motion-Tracking, 2.4Ghz Only, Pan/Tilt Wireless IP Camera, Night Vision, Smart Home ASH21-B
+
ONE MORE?

To get a client's real IP address in PHP, you can use the $_SERVER superglobal variable. More specifically, you can access the REMOTE_ADDR parameter within this variable to obtain the client's IP address.

Here's an example of how you can retrieve the IP address in PHP:

$clientIP = $_SERVER['REMOTE_ADDR'];

By doing this, the $clientIP variable will contain the IP address of the client making the request to your PHP script.

It's important to note that the REMOTE_ADDR value might not always represent the actual client IP address due to various factors, such as if the client is behind a proxy or a load balancer. In such cases, you might need to consider additional headers, such as X-Forwarded-For, to fetch the real IP address. Though, this implementation depends on your specific server setup and configuration.

How do I prevent getting the load balancer's IP address instead of the client's in PHP?

To prevent getting the load balancer's IP address instead of the client's IP address in PHP, you can use the $_SERVER['HTTP_X_FORWARDED_FOR'] header. This header typically contains the original IP address of the client requesting your application.

Here's an example of how you can retrieve the client's IP address when behind a load balancer:

// If the HTTP_X_FORWARDED_FOR header exists if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get the list of IP addresses in the X-Forwarded-For header $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

// The client's IP address will be the first entry in the list
$clientIp = trim($ipList\[0\]);

} else { // If the X-Forwarded-For header doesn't exist, fallback to the remote address $clientIp = $_SERVER['REMOTE_ADDR']; }

// Now you can use $clientIp as the client's IP address echo "Client IP: " . $clientIp;

In this code, $_SERVER['REMOTE_ADDR'] is used as a fallback if the HTTP_X_FORWARDED_FOR header is not present. It retrieves the IP address of the client from the X-Forwarded-For header and handles cases where multiple IP addresses may be present in the header.

Note that this approach assumes that your load balancer is properly configured to pass the client's IP address in the X-Forwarded-For header.

How to differentiate between IPv4 and IPv6 for a client's IP address in PHP?

To differentiate between IPv4 and IPv6 for a client's IP address in PHP, you can use the filter_var() function along with the FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6 flags.

Here is an example of how you can check if an IP address is IPv4 or IPv6:

$clientIP = $_SERVER['REMOTE_ADDR'];

if (filter_var($clientIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { echo 'IPv4 Address'; } elseif (filter_var($clientIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { echo 'IPv6 Address'; } else { echo 'Invalid IP Address'; }

In this code, we first retrieve the client's IP address using $_SERVER['REMOTE_ADDR']. Then, we use the filter_var() function to validate the IP address format. By passing FILTER_VALIDATE_IP as the second argument and either FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 as the third argument, we can check if the IP address is valid IPv4 or IPv6 respectively.

The code will output "IPv4 Address" if the IP address is valid IPv4, "IPv6 Address" if it is valid IPv6, and "Invalid IP Address" if it is neither.

When using a load balancer in PHP, it is recommended to obtain the client's real IP address by checking the HTTP_X_FORWARDED_FOR header. This header is commonly set by load balancers to store the original client IP address. However, it is important to note that this header can be easily spoofed, so it should be used with caution.

Here is an example of how you can obtain the client's IP address in PHP when using a load balancer:

if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Obtain the client's IP address from the X-Forwarded-For header $clientIp = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { // If the X-Forwarded-For header is not set, fallback to the remote address $clientIp = $_SERVER['REMOTE_ADDR']; }

echo "Client IP Address: " . $clientIp;

In this code, the $_SERVER['HTTP_X_FORWARDED_FOR'] variable is checked first to obtain the client's IP address. If this header is set, it means the request has passed through a load balancer, so the value of HTTP_X_FORWARDED_FOR is used. If this header is not set, the code falls back to using $_SERVER['REMOTE_ADDR'] to obtain the client's IP address, which may be the load balancer's IP address instead.

What is the impact of using CDNs on obtaining the real IP address of a client in PHP?

Using Content Delivery Networks (CDNs) can affect the process of obtaining the real IP address of a client in PHP. CDNs act as intermediaries between clients and servers, delivering content from edge servers located in various regions.

When a client makes a request, it typically goes through the CDN's edge server closest to the client, which then forwards the request to the origin server. This process can prevent the origin server from directly seeing the client's real IP address due to the CDN acting as a reverse proxy.

The impact on obtaining the real IP address varies depending on the CDN configuration and the techniques used to extract the IP address. Here are a few scenarios:

  1. Without CDN Configuration: If the CDN is not configured to pass the client's IP address to the origin server, the PHP server receives the IP address of the CDN's edge server instead of the client's real IP address. This can hinder security measures that rely on client IP information, like IP-based blocking/blacklisting.
  2. CDNs with Custom Headers: Some CDNs allow configuring custom HTTP headers to pass the real IP address to the origin server. In PHP, you can use these headers to extract the client's IP address. However, this depends on the CDN provider supporting such functionality and setting up the required headers.
  3. CDN-Provided Variables: Certain CDNs pass the client's IP address in predefined variables, such as $_SERVER['HTTP_X_FORWARDED_FOR'] or $_SERVER['HTTP_CF_CONNECTING_IP']. These variables need to be checked and prioritized when retrieving the client's IP address.

It's essential to handle the extraction of the client's IP address properly in PHP to accommodate various CDN configurations. Relying on server variables may not always provide the correct client IP due to forward proxies and load balancers. Consequently, implementing appropriate IP address extraction techniques, such as parsing X-Forwarded-For headers or considering trusted proxies, can help ensure accuracy when dealing with CDNs.

How to get the true IP address of a visitor in PHP?

To get the true IP address of a visitor in PHP, you can use the $_SERVER superglobal variable. However, keep in mind that it may not always provide the accurate IP address due to various factors such as proxy servers.

Here is an example code snippet that attempts to retrieve the true IP address:

function getIPAddress() { $ipAddress = '';

// Check for shared internet/ISP IP
if (!empty($\_SERVER\['HTTP\_CLIENT\_IP'\]) && $this->validateIPAddress($\_SERVER\['HTTP\_CLIENT\_IP'\])) {
    $ipAddress = $\_SERVER\['HTTP\_CLIENT\_IP'\];
}
// Check for IP passed by proxy
elseif (!empty($\_SERVER\['HTTP\_X\_FORWARDED\_FOR'\])) {
    $ipAddressList = explode(',', $\_SERVER\['HTTP\_X\_FORWARDED\_FOR'\]);
    foreach ($ipAddressList as $address) {
        $address = trim($address);
        if ($this->validateIPAddress($address)) {
            $ipAddress = $address;
            break;
        }
    }
}
// Check for remote address
elseif (!empty($\_SERVER\['REMOTE\_ADDR'\]) && $this->validateIPAddress($\_SERVER\['REMOTE\_ADDR'\])) {
    $ipAddress = $\_SERVER\['REMOTE\_ADDR'\];
}

// Return the IP address
return $ipAddress;

}

function validateIPAddress($ipAddress) { // Validate the IP address using regex or any other method as per your requirements return filter_var($ipAddress, FILTER_VALIDATE_IP); }

This code snippet checks for the HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, and REMOTE_ADDR headers in $_SERVER to retrieve the IP address. It also includes a validateIPAddress function to verify the IP address format.

Note: This method is not foolproof, and the IP address obtained can still be manipulated or obscured by the visitor.

How to handle situations where REMOTE_ADDR variable is overridden by a proxy server in PHP?

When the REMOTE_ADDR variable is overridden by a proxy server in PHP, you can use the HTTP_X_FORWARDED_FOR or HTTP_CLIENT_IP headers to get the original client's IP address. Here's how you can handle such situations:

  1. Check if the 'HTTP_X_FORWARDED_FOR' header is set:

if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $clientIp = trim($ipAddresses[0]); } else { $clientIp = $_SERVER['REMOTE_ADDR']; }

This code checks if the 'HTTP_X_FORWARDED_FOR' header exists and is not empty. If it does, it splits the value by comma (as proxies may append multiple IP addresses) and uses the first IP address as the client's IP. Otherwise, it falls back to the REMOTE_ADDR value.

  1. Check if the 'HTTP_CLIENT_IP' header is also set:

if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) { $clientIp = $_SERVER['HTTP_CLIENT_IP']; }

Some proxies may use the 'HTTP_CLIENT_IP' header to override the client IP. If this header is set, it can be used directly as the client's IP.

  1. Validate the client IP address: It's important to validate the obtained IP address to ensure its correctness and prevent any security vulnerabilities. You can use the 'filter_var()' function with the FILTER_VALIDATE_IP filter to validate the IP address:

if (filter_var($clientIp, FILTER_VALIDATE_IP)) { // Valid client IP address } else { // Invalid client IP address }

This will ensure that the IP address is in a valid format.

By following these steps, you can handle situations where the REMOTE_ADDR variable is overridden by a proxy server in PHP and retrieve the correct client IP address.

How can I determine the actual IP address of a client behind a proxy in PHP?

In PHP, you can use the $_SERVER['HTTP_X_FORWARDED_FOR'] or $_SERVER['HTTP_CLIENT_IP'] variables to determine the actual IP address of a client behind a proxy. However, keep in mind that these values can be manipulated or spoofed by the client or proxy servers.

Here is an example code snippet that demonstrates how you can retrieve the actual IP address:

function getRealIpAddress() { if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Check if multiple IP addresses are present in the header $ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $realIpAddress = trim(end($ipAddresses)); } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) { $realIpAddress = $_SERVER['HTTP_CLIENT_IP']; } else { $realIpAddress = $_SERVER['REMOTE_ADDR']; }

// Remove any potential proxy headers
$realIpAddress = preg\_replace('/\\s\*,\\s\*/', ', ', $realIpAddress);

return $realIpAddress;

}

// Retrieve the IP address $ipAddress = getRealIpAddress();

In this code, the getRealIpAddress() function checks two common proxy headers (HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP) and falls back to REMOTE_ADDR if none of them are present. The function also removes any potential whitespace or additional headers and returns the final IP address.

Please keep in mind that this method may not always be accurate as it relies on the presence and accuracy of the proxy headers set by the client's proxy server.

What is the appropriate technique to get the real IP address of a client in PHP when behind a proxy?

To get the real IP address of a client in PHP when behind a proxy, you can check for specific HTTP headers that may contain the original IP address. Here is an example of a technique to retrieve the real IP address:

function getClientIP() { $ipAddress = '';

if (isset($\_SERVER\['HTTP\_CLIENT\_IP'\]) && !empty($\_SERVER\['HTTP\_CLIENT\_IP'\])) {
    $ipAddress = $\_SERVER\['HTTP\_CLIENT\_IP'\];
} elseif (isset($\_SERVER\['HTTP\_X\_FORWARDED\_FOR'\]) && !empty($\_SERVER\['HTTP\_X\_FORWARDED\_FOR'\])) {
    $ipAddress = $\_SERVER\['HTTP\_X\_FORWARDED\_FOR'\];
} elseif (isset($\_SERVER\['HTTP\_X\_FORWARDED'\]) && !empty($\_SERVER\['HTTP\_X\_FORWARDED'\])) {
    $ipAddress = $\_SERVER\['HTTP\_X\_FORWARDED'\];
} elseif (isset($\_SERVER\['HTTP\_FORWARDED\_FOR'\]) && !empty($\_SERVER\['HTTP\_FORWARDED\_FOR'\])) {
    $ipAddress = $\_SERVER\['HTTP\_FORWARDED\_FOR'\];
} elseif (isset($\_SERVER\['HTTP\_FORWARDED'\]) && !empty($\_SERVER\['HTTP\_FORWARDED'\])) {
    $ipAddress = $\_SERVER\['HTTP\_FORWARDED'\];
} elseif (isset($\_SERVER\['REMOTE\_ADDR'\]) && !empty($\_SERVER\['REMOTE\_ADDR'\])) {
    $ipAddress = $\_SERVER\['REMOTE\_ADDR'\];
}

return $ipAddress;

}

This function checks for common HTTP headers used by proxies (HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, HTTP_X_FORWARDED, HTTP_FORWARDED_FOR, HTTP_FORWARDED) and falls back to REMOTE_ADDR if none of the proxy headers are present.

You can then call the function getClientIP() to retrieve the client's real IP address.

Keep in mind that depending on your server configuration and the specific proxy setup, these headers may not always provide the correct IP address. Therefore, it's recommended to test and validate the results on your specific server environment.

How to retrieve a client's real IP address in PHP?

To retrieve a client's real IP address in PHP, you can use the $_SERVER superglobal variable to access the imported headers from the client's request. However, it's important to note that this method may not always return the actual IP address due to various factors such as load balancers, proxies, and caching servers.

Here is an example of how you can retrieve the client's IP address in PHP:

function getClientIP() { foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $header) { if (array_key_exists($header, $_SERVER) === true) { foreach (array_map('trim', explode(',', $_SERVER[$header])) as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) { return $ip; } } } } }

// Usage $clientIP = getClientIP(); echo "Client's IP address is: " . $clientIP;

In the above example, the function getClientIP() checks multiple headers in $_SERVER array that may contain the client's IP. It starts with the headers commonly used for proxy IP addresses before falling back to REMOTE_ADDR, which typically stores the client's IP address.

By iterating through the headers and validating the IP address using filter_var() with specific filter flags, the function ensures that any private or reserved IP addresses are ignored. It then returns the first valid IP address found.

However, it's important to note that this method relies on the headers provided by the client's request, which can be easily manipulated. Therefore, it is not 100% foolproof, and its accuracy may vary depending on the client's network setup.