简体   繁体   English

无法在数据库中获取正确的 IP 地址

[英]cant get correct ip address into the database

I have the below simple code for inserting some failed login values in my database, but I have some problems:我有以下简单代码用于在我的数据库中插入一些失败的登录值,但我有一些问题:

1- The ip address is being saved in the database as zero no success whatever I do (going crazy on this). 1- ip 地址被保存在数据库中为零,无论我做什么都没有成功(对此很疯狂)。 2- I used current time stamp to get the date and time in a simple query, now that I use prepared statements it doesnt work with it, I am forced to use date('Ymd H:i:s'); 2-我使用当前时间戳在一个简单的查询中获取日期和时间,现在我使用准备好的语句它不能使用它,我被迫使用 date('Ymd H:i:s'); which gives out the wrong time.这给出了错误的时间。

My code is:我的代码是:

<?php
    $username = $_SESSION['Name'];
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $attempted = date('Y-m-d H:i:s');
    $query = "INSERT INTO failed_logins (username, ip_address, attempted) VALUES(?, ?, ?)"; 
    $failed = $conn->prepare($query);
    $failed->bindParam(1, $username);
    $failed->bindParam(2, $ip_address);
    $failed->bindParam(3, $attempted);
    $failed->execute();
?>

My ip_address row in the database is int(11) and it is unsigned.我在数据库中的 ip_address 行是 int(11) 并且它是无符号的。

Any suggestions would help thanks任何建议都会有所帮助谢谢

UPDATE:更新:

I did the below but still no luck:我做了以下但仍然没有运气:

I changed:我变了:

 $ip_address = $_SERVER['REMOTE_ADDR']; 

to this:对此:

 $ip_address = ip2long($_SERVER['REMOTE_ADDR']);

I am forced to use date('Ymd H:i:s');我被迫使用 date('Ymd H:i:s'); which gives out the wrong time.这给出了错误的时间。

Have you tried setting the date_default_timezone_set , ie:您是否尝试过设置date_default_timezone_set ,即:

date_default_timezone_set('America/Los_Angeles');

You cannot use an int to store a var containing dots ans colons .您不能使用int来存储包含冒号的 var。 Change the DB ip_address row from将 DB ip_address行从

int(11)

to

varchar(15); //ipv4

# #

ALTER TABLE `sometable`
MODIFY COLUMN `ip_address` varchar(15);

Or或者

varchar(45); //ipv6

# #

ALTER TABLE `sometable`
MODIFY COLUMN `ip_address` varchar(45);

if you want to store ipv6 addresses如果你想存储ipv6地址


References:参考:

Maximum length of the textual representation of an IPv6 address? IPv6 地址的文本表示的最大长度?

Also maybe to get IP(ish):也可能获得IP(ish):

(string)$ip_address = getRealIpAddr();

function getRealIpAddr() {
    (string)$ip='';
    if (array_key_exists('HTTP_CLIENT_IP', $_SERVER) && !empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
      $ip .= filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP');
    } elseif (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   //to check ip is pass from proxy
      $ip .= filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR');
    } else {
      $ip .= filter_input(INPUT_SERVER, 'REMOTE_ADDR');
    }
    return $ip;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM