PHP 访客唯一标识符生成代码 - 使用设备、系统环境、Cookie 等参数

本文将提供一个 PHP 代码示例,用于根据访客的设备信息、系统环境、Cookie 等参数生成一个唯一的标识符,以便识别访客。

// 获取访客的设备信息
$user_agent = $_SERVER['HTTP_USER_AGENT'];

// 获取访客的 IP 地址
$ip_address = $_SERVER['REMOTE_ADDR'];

// 获取访客的语言设置
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

// 获取访客的操作系统信息
$os = '';
if (preg_match('/windows nt 10/i', $user_agent)) {
    $os = 'Windows 10';
} elseif (preg_match('/windows nt 6.2/i', $user_agent)) {
    $os = 'Windows 8';
} elseif (preg_match('/windows nt 6.1/i', $user_agent)) {
    $os = 'Windows 7';
} elseif (preg_match('/windows nt 6.0/i', $user_agent)) {
    $os = 'Windows Vista';
} elseif (preg_match('/windows nt 5.1/i', $user_agent)) {
    $os = 'Windows XP';
} elseif (preg_match('/windows nt 5.0/i', $user_agent)) {
    $os = 'Windows 2000';
} elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
    $os = 'Mac OS X';
} elseif (preg_match('/linux/i', $user_agent)) {
    $os = 'Linux';
}

// 获取访客的浏览器信息
$browser = '';
if (preg_match('/msie/i', $user_agent) && !preg_match('/opera/i', $user_agent)) {
    $browser = 'Internet Explorer';
} elseif (preg_match('/firefox/i', $user_agent)) {
    $browser = 'Firefox';
} elseif (preg_match('/chrome/i', $user_agent)) {
    $browser = 'Google Chrome';
} elseif (preg_match('/safari/i', $user_agent)) {
    $browser = 'Safari';
} elseif (preg_match('/opera/i', $user_agent)) {
    $browser = 'Opera';
} elseif (preg_match('/netscape/i', $user_agent)) {
    $browser = 'Netscape';
}

// 生成唯一标识符
$unique_id = md5($user_agent . $ip_address . $language . $os . $browser . time());

// 设置 cookie,有效期为1个月
setcookie('unique_id', $unique_id, time() + 30 * 24 * 60 * 60);

// 输出唯一标识符
echo $unique_id;

这段代码首先从服务器变量中获取用户代理、IP 地址、语言设置,然后使用正则表达式从用户代理中提取操作系统和浏览器信息。最后,将这些信息与当前时间戳一起使用 MD5 哈希算法生成一个唯一的标识符,并将其存储在 Cookie 中。

需要注意的是,这种方法并非绝对可靠,因为用户可以手动修改他们的浏览器设置或使用代理服务器来隐藏他们的真实信息。

如果您需要更可靠的访客识别方法,可以考虑使用第三方服务,例如 Google Analytics 或 Facebook Pixel。

PHP 访客唯一标识符生成代码 - 使用设备、系统环境、Cookie 等参数

原文地址: https://www.cveoy.top/t/topic/mEA1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录