如何使用getCountryFromIP PHP函数来知道用户的位置,并根据它显示按钮


how to use getCountryFromIP PHP function to know users location and display button based on it?

我有一个PHP函数

<?php
    function getCountryFromIP($ip, $type = "code"){
        $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
        $details = get_object_vars($details);
        $country = $details["country"];
        return $country;
    }
?>

现在我想使用这个函数来获取用户的位置,并基于该位置显示一个特定的按钮,该按钮将根据用户的位置将用户带到相应的PDF。

在我的html中,我有这个

<div class="locbuttons">
    <a class="btn btn-large trial-button" href="/ebooks/EUConsultantsPack.pdf" target="_blank"><button>Consultant's Pack</button></a>
    <a class="btn btn-large trial-button" href="/ebooks/USConsultantsPack.pdf" target="_blank"><button>Consultant's Pack</button></a>
</div>

这里假设获取国家/地区的函数有效。

你可能要使用一个数组,并匹配国家(在你的数组)与电子书。

<?php
$dataArray = array(
array("Country" =>"United Kingdom", "pdf" => "/ebooks/EUConsultantsPack.pdf"),
array("Country" => "Germany", "pdf" => "/ebooks/EUConsultantsPack.pdf"),
array("Country" => "United States of America", "pdf" => "/ebooks/USConsultantsPack.pdf")
);
?>

然后,一旦调用函数并检索用户国家....

<?php
$country = getCountryFromIP($ip);
foreach($dataArray as $dA){
  if ($country == $dA['Country']){
  //if the country matches our array, we can print out the correct button
     echo '<a class="btn btn-large trial-button" href="'.$dA['pdf'].'" target="_blank"><button>Consultant''s Pack</button></a>';
  }
}
?>