Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_SERVER['REMOTE_ADDR'] not giving the right ip address

Tags:

php

localhost

ip

I'm making a form with PHP and I want to keep record of the User's IP Addresses. This is the snip-it of code I used:

<input type="hidden" name="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>" />

When I open the code up in XAMPP and read the source, the value had an IP address different than what was mine:

<input type="hidden" name="ip" value="::1" />

Does this IP address normally happen when I use it in a localhost (XAMPP)?
If not, are there any alternatives into grabbing the user's IP address?

like image 691
zeldarulez Avatar asked Jun 11 '12 14:06

zeldarulez


People also ask

What is $_ server [' Remote_addr '];?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page.

Can $_ server Remote_addr be spoofed?

Any $_SERVER variable can be spoofed - e.g. curl_setopt( $ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip")); So it depends entirely on the context: if the attacker is expecting a response, it will go back to $ip. If they don't care about the response, they can certainly spoof the header.

What is Remote_addr header?

Returns the IP address of the remote host making the request. This variable is specific to the current gateway program request. Type and Usage. "Environment Variables"


2 Answers

IP ::1 is "localhost" in IPv6 version. Your machine is configured with IPv6 - and hence you're getting this IP address. Probably, when you deploy your application on the live server, IPv6 will not be configured on the server and your app will get a more familiar IPv4 address (e.g. aaa.bbb.ccc.ddd).

On another note, $_SERVER['REMOTE_ADDR'] may not always contain the right address. It's better to use:

if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip_address = $_SERVER['REMOTE_ADDR'];
}
like image 183
Aleks G Avatar answered Sep 21 '22 16:09

Aleks G


<input type="hidden" name="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>" />

Don't do that. Get the request from $_SERVER when the form is submitted. Getting it when the form is generated and storing it in the form just gives people the opportunity to change it.

Does this IP address normally happen when I use it in a localhost (XAMPP)?

Yes. Getting the local IP (IPv6) address is normal when you request a page from localhost.

like image 26
Quentin Avatar answered Sep 21 '22 16:09

Quentin