根据GEO位置从不同目录中挑选随机图像

时间:2018-07-06 14:00:43

标签: php cloudflare

从目录中选择随机图像的代码非常简单。

例如;我当前的代码是:

<?php
$imagesDir = 'img/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)]; // See comments
?>

我想使用Cloudflare的GEO IP查找器,因此,当用户访问网站时,它会反馈用户的来源。

所以说我想要,

  if england use directory > img/en/ 
  if australia use directory > img/au/
  if USA use directory > img/usa/
  if NZ use directory > img/nz/
  if any other country > img/

我知道它的逻辑,但是将其放入代码中是我一直在努力的另一件事。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

创建位置目录及其对应名称的数组,然后根据地理位置(在我的示例中为$location)构建图像目录。

$location = 'australia';

$dirs = array('england'   => 'en',
              'australia' => 'au',
              'USA'       => 'usa',
              'NZ'        => 'nz');

$imagesDir = 'img/' . (isset($dirs[$location]) ? $dirs[$location] . '/' : '');

如果在数组中未找到位置,则$imagesDir变量的设置将默认为现在的img/

答案 1 :(得分:0)

基本上,您只是在尝试转换“ england”-> img / zh / 像这样的任何直接转换,我都喜欢使用字典/地图(取决于语言),或者对于PHP使用associative arrays。使用三元数,如果键(国家/地区)不在数组中,则为“ img /”

$arr = [
   "england" => "img/en/",
   //...
];
$imagesDir = in_array($COUNTRY, $arr) ? $arr[$COUNTRY] : "img/";