PHP 中的用户时区问题修复


User Timezone Issue Fix in PHP

我正在开发一个php应用程序,我需要在其中检测用户timzone(他们从哪里访问应用程序)。我已经尝试了JavaScript时区检测方法,如果用户更改了时区或机器时间,这将影响我的计算,我将面临的问题。

我想避免对系统时间的依赖。请对此提供任何替代方法的建议。

谢谢。

在使用 IP2Location 的 DB11 数据库之前,我已经完成了此操作,该数据库允许您根据用户的 IP 地址查找用户的时区。他们有一个免费版本,您可以使用它进行测试,但它不如付费版本准确。您可以从 https://lite.ip2location.com/database-ip-country-region-city-latitude-longitude-zipcode-timezone 下载它,它包含该页面上的说明,用于根据您使用的数据库类型进行设置。

假设您正在将MySQL与php一起使用,这里有一些示例代码可以帮助您在设置数据库后开始。至少您必须将$ServerName、$DbLogin和$DbPassword变量更改为您自己的设置,以便与数据库建立正确的连接:

<?
/* function to convert ip address in x.x.x.x format to integer/long for use with the ip2location database */
function convertIpToLong($ip) {
    return sprintf("%u", ip2long($ip));
}
$ServerName = "localhost";  // change to real mysql ip
$DatabaseName = "ip2location";
$DbLogin = "root";      // change to a db user that has read permission to your new database
$DbPassword = "password";   // change to your db user password
$link = mysqli_connect($ServerName, $DbLogin, $DbPassword);
// connect to database
mysqli_select_db($link, $DatabaseName)
    or die("Could not select database");
$ipAddress = convertIpToLong('8.8.8.8');    // change to real ip address here
$query = "SELECT * FROM ip2location_db11 WHERE ".$ipAddress." >= ip_from AND ".$ipAddress." <= ip_to;";
// test if the ip address is matched to one in the database
if (mysqli_multi_query($link, $query)) {
    $result = mysqli_store_result($link);   // found a match
}
else {
    die("Query failed : " . mysqli_error($link));
}
$row = mysqli_fetch_array($result); // load results into row variable
mysqli_free_result($result);    // clear resultset
// write each column to the screen
foreach ($row as $key => $val) {
    echo $key." = ".$val."<br />";
}
?>