Home » Php » apache – PHP $_SERVER['REMOTE_ADDR'] empty

apache – PHP $_SERVER['REMOTE_ADDR'] empty

Posted by: admin July 12, 2020 Leave a comment


Somehow $_SERVER['REMOTE_ADDR'] returns an empty string, i have the same code (as part of a script) running on multiple servers and it works everywhere else, they are all the same setup.

The weird thing is, when I restart apache and load the page, it works exactly once, if I reload the site + all the times after that, it’s empty. I’ve had other people try, same result, empty.

someone suggested it was something with IPv6 configuration, I have now completely disabled IPv6 but the problem persists.

How to&Answers:

if you’re behind a proxy server, you can use $_SERVER['HTTP_X_FORWARDED_FOR'] or $_SERVER['HTTP_CLIENT_IP'] instead of $_SERVER['REMOTE_ADDR'].
this will depends on how your proxy is configured.


Yes it’s possible for REMOTE_ADDR to be empty.
so if you want you can use this code that I use to get the ip based on HTTP_X_FORWARDED_FOR

    if(! empty($_SERVER['REMOTE_ADDR']) ){
    $ip = $_SERVER['REMOTE_ADDR'];

I’m checking REMOTE_ADDR first as it is more reliable and sometimes HTTP_X_FORWARDED_FOR can be spoofed by users


I had code on a new VM that looked like this. It is being called from a javascript file:

$hostip = $_SERVER['REMOTE_ADDR'];
var myip = "<?=$hostip ?>";

Worked on the old server of course and I was scratching my head for a while thinking there was something wrong with Apache..Was there a module missing? Some obscure Apache setting I can’t find?. I thought Apache wasn’t sending on the Server variables. That was until I tried the plain ol’ fashioned way and it worked:


Turned out I had to edit php.ini and set short_open_tag to On. Facepalm – the shortcut php tags weren’t working. Hopefully that will help save someone else a head of time 🙂