title: PHP most accurate / safe way to get real user IP address in 2017
body: <p>What is the most accurate way to get user's IP address in 2017 via PHP?</p>
  
  <p>I've read a lot of SO questions and answers about it, but most of answers are old and commented by users that these ways are unsafe.</p>
  
  <p>For example, take a look at this question (2011): <a href="https://stackoverflow.com/questions/3003145/how-to-get-the-client-ip-address-in-php">How to get the client IP address in PHP?</a></p>
  
  <p>Tim Kennedy's answer contains a recommendation to use something like: </p>
  
  <pre><code>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'];
  }
  </code></pre>
  
  <p>But as I've read a lot, I have seen that to use <code>X_FORWARDED_FOR</code> is unsafe, as the comment below highlights: </p>
  
  <blockquote>
    <p>Do NOT use the above code unless you know EXACTLY what it does! I've
    seen MASSIVE security holes due to this. The client can set the
    X-Forwarded-For or the Client-IP header to any arbitrary value it
    wants. Unless you have a trusted reverse proxy, you shouldn't use any
    of those values.</p>
  </blockquote>
  
  <p>As I didn't know EXACTLY what it does, I don't want to take the risk. He said it is unsafe, but did not provide a safe method to get user's IP address.</p>
  
  <p>I've tried the simple <code>$_SERVER['REMOTE_ADDR'];</code>, but this returns the wrong IP. I've tested this and my real IP follows this pattern: <code>78.57.xxx.xxx</code>, but I get an IP address like: <code>81.7.xxx.xxx</code></p>
  
  <p>So do you have any ideas?</p>