Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP $_SERVER['REMOTE_ADDR'] empty

Tags:

php

apache

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.

like image 747
Marius Prollak Avatar asked Aug 01 '13 21:08

Marius Prollak


2 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.

like image 69
onionpsy Avatar answered Sep 17 '22 11:09

onionpsy


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

<?php
    if(! empty($_SERVER['REMOTE_ADDR']) ){
    $ip = $_SERVER['REMOTE_ADDR'];
}
else{
    $ip = empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? '' : $_SERVER['HTTP_X_FORWARDED_FOR'];
}

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

like image 29
fedmich Avatar answered Sep 17 '22 11:09

fedmich