php - Picking a random image out of different directories based on GEO locations
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?
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).If a location is not found in the array the setting of the
$imagesDir
variable will default toimg/
as it is now.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/"