PHP and JavaScript both are different languages. PHP is a server side language while JavaScript is a client-side language. In this tutorial, I am going to show you how you can get the user IP Address with the help of these languages.
First of all, I am going to show you the PHP code. How you can get the IP address of the client in PHP?
Remember:
There are different types of users behind the Internet, so we want to catch the IP address from different portions. Those are:
1. $_SERVER['REMOTE_ADDR']
– This contains the real IP address of the client. That is the most reliable value you can find from the user.
2. $_SERVER['HTTP_CLIENT_IP']
– This will fetch the IP address when the user is from shared Internet services.
3. $_SERVER['HTTP_X_FORWARDED_FOR']
– This will fetch the IP address from the user when he/she is behind the proxy.
4. $_SERVER['REMOTE_HOST']
– This will fetch the hostname from which the user is viewing the current page. But for this script to work, hostname lookups on inside httpd.conf must be configured.
So we can use this following combined function to get the real IP address from users who are viewing in different positions.
<?php
// Function to get the user IP address
function getUserIP() {
$userIP = '';
if(isset($_SERVER['HTTP_CLIENT_IP'])){
$userIP = $_SERVER['HTTP_CLIENT_IP'];
}elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
}elseif(isset($_SERVER['HTTP_X_FORWARDED'])){
$userIP = $_SERVER['HTTP_X_FORWARDED'];
}elseif(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])){
$userIP = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
}elseif(isset($_SERVER['HTTP_FORWARDED_FOR'])){
$userIP = $_SERVER['HTTP_FORWARDED_FOR'];
}elseif(isset($_SERVER['HTTP_FORWARDED'])){
$userIP = $_SERVER['HTTP_FORWARDED'];
}elseif(isset($_SERVER['REMOTE_ADDR'])){
$userIP = $_SERVER['REMOTE_ADDR'];
}else{
$userIP = 'UNKNOWN';
}
return $userIP;
}
?>
Now you need to call the above function to get the user IP. To call the above function you just to write below code line.
<?php echo getUserIP(); ?>
How to get IP address in JavaScript.
You can get an IP address in JavaScript (JQuery) using getJSON(). If you need to get an IP address in your JS file you can get easily. In this example, you can see how to get an IP address in JQuery.
The below code is dependent on JQuery library. So first you need to add JQuery in the head tag. Get JQuery lib CDN form here.
<h1>Your Ip Address : <span class="ip"></span></h1>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("https://api.ipify.org/?format=json", function(e) {
$('.ip').text(e.ip);
});
});
</script>