php

How to get the client IP address in PHP

In this tutorial, we are going to see how to get the client IP address in PHP. We often need to collect the client’s IP address to track activity and for security reasons. It is very easy to get the IP address of the visitor in PHP. The PHP variable $_SERVER makes it easy to get the IP address of the user.

The easiest way to get the IP address of the visitor is to use REMOTE_ADDR in PHP.

$_SERVER[‘REMOTE_ADDR’] – Returns the IP address of the user from which the current page is displayed.
 

Example 1: How to get the client IP address in PHP
<?php
	echo 'The client\'s IP address is : '.$_SERVER['REMOTE_ADDR'];
?>

Output:

The client's IP address is : 192.168.1.101

Sometimes REMOTE_ADDR does not return the correct IP address for the user. The reason behind this is the use of a Proxy. In this case, use the following code to get the user’s real IP address in PHP.
 

 

Example 2: How to get the client IP address in PHP
<?php
	function getIp(){
		if(!empty($_SERVER['HTTP_CLIENT_IP'])){
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}else{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}

	echo 'The client\'s IP address is : '.getIp();
?>

Output:

The client's IP address is : 192.168.1.101
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *