Get IP Address in PHP

by  
Share:
php

There’s a lot of approaches to get the IP address in PHP. Sometimes, it can be necessary to log the IP address of a user to fulfill certain business logic, such as logging, IP-based features that a company offers.

The most most straightforward way to get the get the IP address in PHP is to use $_SERVER['REMOTE_ADDR']

<?php
echo $_SERVER['REMOTE_ADDR'];
?>

Another alternative is to use HTTP_X_FORWARDED_FOR, but I am not sure about this since HTTP_X_FORWARDED_FOR can be anything a client chooses to set, whereas REMOTE_ADDR is much harder to fake.

<?php
 $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    echo $ipaddress;
?>

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.