php - Picking a random image out of different directories based on GEO locations

593

The code for picking an random image out of a directory is pretty straight forward.

For example; my current code is this:

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

I want to use Cloudflare's GEO IP finder, so when the user visits the website it feeds back where the users from.

So let's say I want,

  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/

I know the logic to it, but putting it into code is another thing which i've been struggling to do.

Any ideas?

809

Answer

Solution:

Create an array of the location directories and their corresponding names then build your image directory based on the geo location ($location in my example).

$location = 'australia';

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

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

If a location is not found in the array the setting of the$imagesDir variable will default toimg/ as it is now.

780

Answer

Solution:

Essentially, you are just trying to convert "england" -> img/en/ Any straight conversion, like this, I like to use a dictionary/map (depending on the language), or associative arrays for PHP. Uses a ternary, if the key (country) is not in the array, then "img/"

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

People are also looking for solutions to the problem: html - How to Recover Bitnami Stack php application from windows 7

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.