在php中使用ip地址获取当前国家名称 [英] Fetching the current country name using ip address in php

查看:89
本文介绍了在php中使用ip地址获取当前国家名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉菜单,我从数据库中获取国家名称,我想根据下拉框中的 IP 地址选择当前国家/地区名称

I have a dropdown in which i fetch country name from database and i want to select current country name based on there ip address in dropdown box

推荐答案

使用 PHP GeoIP API.注意:您需要先设置Maxmind GeoIP API 数据库,然后才能使用这些功能.

Use PHP GeoIP API. NOTE: you need to setup the Maxmind GeoIP API database before you can use the functions.

<select name="securityqustion"  class="securityqustion" id="security_qustion">
<?php
  // will resolve 2-character ISO country code
  $request_country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);  

  $countries = array("DE" => "Germany", "FR" => "France", ...);  // define list
  foreach ($countries as $country_code => $country_label) {
    if ($request_country == $country_code) 
      $selected = "selected"
    else 
      $selected = "";
    echo "<option value=\"{$country_code}\" {$selected}>{$country_label}</option>\n";
  }
?>
</select>

这篇关于在php中使用ip地址获取当前国家名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆