0

So far I’m looking into using ipify’s php api for returning an ip but every time I try it returns my website ip. I want it to show user ip instead what can I do to fix that?

Here’s the code:

<?php
    $ip = file_get_contents('https://api4.ipify.org');
    echo "My public IP address is: " . $ip;
?>

Edit:

I understand there is this way of doing it

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    echo "My public IP address is: " . $ip;
?>

but i prefer $_SERVER["HTTP_CF_CONNECTING_IP"] and doing so they dont always return 1pv4. Is there any way to make it enforce ipv4 format without modifying website settings?

  • That's because PHP is a _server side_ language (gets executed on the server), so it's your server that makes that request, not the client (the users browser). – M. Eriksson Aug 21 '22 at 09:01

2 Answers2

2

This should do it, no need for the API to access the IP address of the user:

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    echo "My public IP address is: " . $ip;
?>

Something to note though, is that this method will get whatever the IP is, so if they are using a VPN or Proxy, you will get the IP of that service.

  • _"if they are using a VPN or Proxy, you will get the IP of that service."_ - That's rarely an issue since that is the users public IP. Something to point out is that if _your_ site is behind a proxy/load balancer or similar, then `$_SERVER['REMOTE_ADDR']` will contain _that_ IP instead of the users. – M. Eriksson Aug 21 '22 at 09:09
  • I get theres that way of doing it but i prefer to use `$_SERVER["HTTP_CF_CONNECTING_IP"];` and it dont always return in ipv4 format. Is there anything i can do to strictly get it to enforce ipv4 like https://api4.ipify.org does without modifying my website settings? – g0tTr0LLed Aug 21 '22 at 18:33
0

Nevermind i originally didnt wanna modify web settings but i secure my website with cloudflare and they give option 'Pseudo IPV4' and i set it to 'overwrite headers' and so far i havent got any ipv6 only ipv4