How to Get the Client IP Address in PHP

09/07/2021

Contents

In this article, you will learn how to get the client IP address in PHP.

Using the $_SERVER superglobal array

The client’s IP address can be obtained in PHP using the $_SERVER superglobal array. The $_SERVER superglobal array holds information about the web server and the current request. It contains information such as the headers, paths, and script locations. The $_SERVER[‘REMOTE_ADDR’] key holds the IP address of the client making the request to the server.

Here’s an example of how to get the client’s IP address:

<?php
  $clientIP = $_SERVER['REMOTE_ADDR'];
  echo "Your IP address is: " . $clientIP;
?>

Note that this may not always be the correct IP address, as the client may be behind a proxy. In that case, you can try using $_SERVER[‘HTTP_X_FORWARDED_FOR’] to get the client’s IP address.

<?php
  $clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
  echo "Your IP address is: " . $clientIP;
?>

It’s important to note that the value of $_SERVER[‘HTTP_X_FORWARDED_FOR’] can be easily manipulated and may not always be trustworthy, so it’s important to validate the IP address before using it.

Here’s an example of how to get the client’s IP address while accounting for potential proxy use:

<?php
  // Get the client's IP address
  $clientIP = $_SERVER['REMOTE_ADDR'];

  // Check if the client is behind a proxy
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    // If so, use the X-Forwarded-For header
    $clientIP = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
  }

  echo "Your IP address is: " . $clientIP;
?>