idexo
idexo

Reputation: 63

Is this the right way to grab IP when form submitted?

I did find some info about saving IP and I came up with the code below:

// IP GRAB
$http_client_ip = $_SERVER['HTTP_CLIENT_IP']; //MORE RELIABLE IP
$http_x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR']; //ALSO MORE RELIABLE
$remote_addr = $_SERVER['REMOTE_ADDR']; //NOT RELIABLE BCS IT MAY BE A SHARED NETWORK OR BEHIND A PROXY

if (!empty($http_client_ip)) {
    $ip_address = $http_client_ip;
} else if (!empty($http_x_forwarded_for)) {
    $ip_address = $http_x_forwarded_for;
} else {
    $ip_address = $remote_addr;
}

$ip = ip2long($ip_address);

I'd like to grab the user's IP address when the user push to submit button/sent form. I also want to save this IP to the table on the database. So I made an IP column on the table as INT(11) UNSIGNED(This was recommended for somebody else on here.)

In short: Am I doing it right?

Upvotes: 1

Views: 1452

Answers (2)

idexo
idexo

Reputation: 63

This is what I came up after some more search:

I changed the INT(11)UNSIGNED to VARCHAR(45) and I just save IP without using ip2long(); the rest is the same as it was before. Now it adds ::1 to the IP column on the table when I post a test. I assume it works alright and I'll check it out when I actually publish the site.

note: I'll accept this answer when it becomes available. Thank you for your time.

Upvotes: 0

Maytham Fahmi
Maytham Fahmi

Reputation: 33397

Your code can extended, the follow function could be used to get client IP:

function get_client_ip() {

    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if ($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if ($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if ($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

    return $ipaddress;
}

It is also not necessary to change your the IP to long (ip2long), only if you have a reason to do it.

And I will save it as String (VARCHAR) in database.

Upvotes: 1

Related Questions