获取访问者IP地址
734人阅读 admin发布于2023年12月25日 分类:PHP
ip.html
<script> var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.ipify.org', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { var ip = xhr.responseText; console.log(ip); // 将ip地址写入数据库 xhr.open('POST', '/writeip.php', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log('IP地址写入成功'); } else { console.error(xhr.statusText); } } }; xhr.send('ip=' + encodeURIComponent(ip)); } else { console.error(xhr.statusText); } } }; xhr.send(null); </script>
writeip.php
<?php $ip = $_SERVER['REMOTE_ADDR']; // 通过HTTP请求头中的Remote_Addr获取访问者ip //$ip = $_POST['ip']; // 通过ip.html返回ip,再保存到数据 // 连接数据库 $db_host = "localhost"; $db_user = "db_ip"; $db_pass = "12345678"; $db_name = "ip_info"; $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 查找最后一个IP,判断和$ip是否相同,相同不处理,不相同则插入新的IP $sql = "SELECT * FROM ip_info order by id DESC LIMIT 1"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0) { // 遍历查询结果 while ($row = mysqli_fetch_assoc($result)) { $oip = $row["ip"]; } } if(!isset($oip) || $oip != $ip) { // 不相同由插入新IP $stmt = $conn->prepare("INSERT INTO ip_info (ip) VALUES (?)"); $stmt->bind_param("s", $ip); $stmt->execute(); $stmt->close(); } $result->close(); $conn->close(); ?>
觉得有用 打赏一下
支付宝扫一扫打赏

微信扫一扫打赏

本文地址:http://www.xnamp.com/portal/article/index.html?id=15 转载请注明来源
标签:
上一篇: 路由器和三层交换机区别
下一篇: PHP获取用户访问IP地址的5种方法
评论 0