Skip to content
Fix Code Error

Get the client IP address using PHP

March 13, 2021 by Code Error
Posted By: Anonymous

I want to get the client IP address who uses my website. I am using the PHP $_SERVER superglobal:

$_SERVER['REMOTE_ADDR'];

But I see it can not give the correct IP address using this. I get my IP address and see it is different from my IP address and I can also see my IP address in some website like:

http://whatismyipaddress.com/

I paste the IP address which give my PHP function but this website shows no result about this. How does this problem come about and how can I get IP address of the client?

Solution

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}
Answered By: Anonymous

Related Articles

  • Reference — What does this symbol mean in PHP?
  • How to save and extract session data in codeigniter
  • how to fix Invalid request (Unsupported SSL request)…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How to get Real IP from Visitor?
  • Getting visitors country from their IP
  • PHP $_SERVER['HTTP_HOST'] vs.…
  • Smart way to truncate long strings
  • How to find out if you're using HTTPS without…
  • PHP parse/syntax errors; and how to solve them
  • How does PHP 'foreach' actually work?
  • Request string without GET arguments
  • How do I count unique visitors to my site?
  • Get the full URL in PHP
  • What is your most productive shortcut with Vim?
  • How do you parse and process HTML/XML in PHP?
  • Maximum length of the textual representation of an…
  • How to make vim paste from (and copy to) system's clipboard?
  • How to filter a RecyclerView with a SearchView
  • How to get a user's client IP address in ASP.NET?
  • Php mailer working with utf-8 locally but not on host
  • import error: 'No module named' *does* exist
  • Examples of GoF Design Patterns in Java's core libraries
  • Reference - What does this regex mean?
  • Apache server keeps crashing, "caught SIGTERM,…
  • Access-Control-Allow-Origin is not allowed by…
  • Why does C++ code for testing the Collatz conjecture…
  • JavaScript - XMLHttpRequest,…
  • How to calculate the difference between two dates using PHP?
  • How to copy and paste code without rich text formatting?
  • how to create a logfile in php?
  • data.table vs dplyr: can one do something well the…
  • nginx / docker / ssl for localhost
  • Best practice multi language website
  • How do I get the base URL with PHP?
  • How do I get user IP address in django?
  • The definitive guide to form-based website authentication
  • How to register a custom callback after Ember.RSVP.hash
  • enable cors in .htaccess
  • XMLHttpRequest cannot load ✘✘✘ No…
  • SQL query return data from multiple tables
  • How do I return the response from an asynchronous call?
  • What are the undocumented features and limitations…
  • Start redis-server with config file
  • AngularJS $http, CORS and http authentication
  • How to generate a random string of a fixed length in Go?
  • var_dump $_SERVER['HTTP_HOST'] shows expected…
  • "Thinking in AngularJS" if I have a jQuery background?
  • What's the best way of scraping data from a website?
  • Set up DNS based URL forwarding in Amazon Route53
  • Callback functions in C++
  • How can I programmaticaly copy text from notepad and…
  • v-show doesn't work as expected
  • How can I find the product GUID of an installed MSI setup?
  • Insert PHP code In WordPress Page and Post
  • SPA best practices for authentication and session management
  • "requests-html" proxy setting not working
  • What is an optional value in Swift?
  • Ukkonen's suffix tree algorithm in plain English
  • What is the origin of foo and bar?
  • Convert a PHP script into a stand-alone windows executable
  • Why am I having image overlap issues while using…
  • Best approach to real time http streaming to HTML5…
  • Ubuntu apt-get unable to fetch packages
  • How can I manually compile a svelte component down…
  • Execute a PHP script from another PHP script
  • How to serve all existing static files directly with…
  • What is a NullReferenceException, and how do I fix it?
  • How can I apply a piece of R code to every column of…
  • "Notice: Undefined variable", "Notice: Undefined…
  • trying to create a dynamic swiper
  • How to dispatch a Redux action with a timeout?
  • What are the real-world strengths and weaknesses of…
  • Get IP address of visitors using Flask for Python
  • PHP how to get the base domain/url?
  • Logging best practices
  • How do I connect to this localhost from another…
  • How to make a great R reproducible example
  • Memcached vs. Redis?
  • Getting the closest string match
  • How to paste yanked text into the Vim command line
  • How do I merge two dictionaries in a single…
  • For-each over an array in JavaScript
  • How to "properly" create a custom object in JavaScript?
  • How do I rotate text in css?
  • getting error while updating Composer
  • Avoid creating new session on each axios request laravel
  • How to find out client ID of component for ajax…
  • ember.js, ember-cli: Outlets not nesting properly
  • How to validate Google reCAPTCHA v3 on server side?
  • What are the new features in C++17?
  • Database development mistakes made by application developers
  • JavaScript get clipboard data on paste event (Cross browser)
  • jQuery Mobile: document ready vs. page events
  • Getting started with Haskell
  • Secure hash and salt for PHP passwords
  • Turning off auto indent when pasting text into vim
  • How to use Servlets and Ajax?
  • PHP - Failed to open stream : No such file or directory
  • How to get client IP address in Laravel 5+

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to extract the substring between two markers?

Next Post:

Send email using the GMail SMTP server from a PHP page

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error