Currently I get usr's IP like this:
if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif ( isset($_SERVER['REMOTE_ADDR']) ) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IPs
+----+----------------+-------------+
| id | user_ip | date_time |
+----+----------------+-------------+
| 1 | 43.12.9.9 | 1468070172 |
| 2 | 173.3.0.1 | 1468070667 |
+----+----------------+-------------+
But now, I read this in here:
if you are going to save the
$_SERVER['HTTP_X_FORWARDED_FOR']
, make sure you also save the$_SERVER['REMOTE_ADDR']
value. E.g. by saving both values in different fields in your database.
So I'm changing my code to this:
$remote_add = $_SERVER['REMOTE_ADDR']; // I don't use isset() for this becase it is always set
$http_x_forwarded_for = isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
// IPs
+----+----------------+----------------+-------------+
| id | remote | forwarded | date_time |
+----+----------------+----------------+-------------+
| 1 | 43.12.9.9 | NULL | 1468070172 |
| 2 | 93.35.40.1 | 173.3.0.1 | 1468070667 |
+----+----------------+----------------+-------------+
Ok what I'm doing is correct? I'm asking this because a few professional programmers tell me what you doing is useless and you need just on column as user's IP. Well may please someone clear me up? How can I get user's IP correctly?
My final code:
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $header){
$header = trim($header); // just to be safe
if (filter_var($header, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
$header = $header;
}
}
}
}
$user_ip = $_SERVER['REMOTE_ADDR'];
// IPs
+----+----------------+----------------+-------------+
| id | user_ip | header | date_time |
+----+----------------+----------------+-------------+
| 1 | 43.12.9.9 | NULL | 1468070172 |
| 2 | 93.35.40.1 | 173.3.0.1 | 1468070667 |
+----+----------------+----------------+-------------+