How to get the client IP address in PHP?

 

In PHP, you can obtain the client's IP address using the $_SERVER superglobal variable. The client's IP address can be found in the $_SERVER['REMOTE_ADDR'] element. Here's an example of how to get the client's IP address in PHP:

php
<?php // Get the client's IP address $client_ip = $_SERVER['REMOTE_ADDR']; // Print the client's IP address echo "Client IP Address: " . $client_ip; ?>

In this example:

  1. We access the $_SERVER superglobal variable.

  2. We retrieve the client's IP address using $_SERVER['REMOTE_ADDR'], which stores the IP address of the client making the request to your PHP script.

  3. We store the client's IP address in the $client_ip variable.

  4. Finally, we print the client's IP address using echo.

When you run this PHP script, it will display the client's IP address in the browser or wherever you are running the script. Note that the accuracy of $_SERVER['REMOTE_ADDR'] depends on the client's network configuration and whether they are behind a proxy or firewall, so it may not always reflect the actual client IP address in every scenario.

Comments