用代码记录访客信息并在后台展示

Published
2023-02-13
浏览次数 :  114

function record_visitor_ip() {
//实现根据ip地址只记录一次,如果ip已存在,就不再记录
  $visitor_ip = $_SERVER['REMOTE_ADDR'];

  $visitor_ips = get_option('visitor_ips');
  if (empty($visitor_ips)) {
    $visitor_ips = array();
  }

  $found = false;
  foreach ($visitor_ips as $visitor_info) {
    if ($visitor_info['ip'] === $visitor_ip) {
      $found = true;
      break;
    }
  }

  if (!$found) {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $country = '';

    $ip_info = file_get_contents('http://ip-api.com/json/' . $visitor_ip);
    if ($ip_info) {
      $ip_info = json_decode($ip_info, true);
      if ($ip_info && $ip_info['status'] == 'success') {
        $country = $ip_info['country'];
      }
    }

    $visitor_info = array(
      'ip' => $visitor_ip,
      'browser' => $user_agent,
      'country' => $country,
      'time' => time()
    );

    array_push($visitor_ips, $visitor_info);
    update_option('visitor_ips', $visitor_ips);
  }
}
add_action('wp_head', 'record_visitor_ip');

function add_visitor_ips_page() {
  add_menu_page(
    'Visitor IPs',
    'Visitor IPs',
    'manage_options',
    'visitor-ips',
    'display_visitor_ips_page',
    'dashicons-admin-generic',
    30
  );
}
add_action('admin_menu', 'add_visitor_ips_page');

function display_visitor_ips_page() {
  $visitor_ips = get_option('visitor_ips');
  if (!empty($visitor_ips)) {
    echo '<table class="wp-list-table widefat striped">';
    echo '<thead><tr><th>Visitor IP</th><th>Browser</th><th>Country</th><th>Time</th></tr></thead>';
    echo '<tbody>';
    foreach ($visitor_ips as $visitor_info) {
      echo '<tr><td>' . $visitor_info['ip'] . '</td>';
      echo '<td>' . $visitor_info['browser'] . '</td>';
      echo '<td>' . $visitor_info['country'] . '</td>';
      echo '<td>' . date('Y-m-d H:i:s', $visitor_info['time']) . '</td></tr>';
    }
    echo '</tbody>';
    echo '</table>';
  } else {
    echo '<p>No visitor IPs found.</p>';
  }
}

  • 标签1
  • 标签1
  • 标签1
Top