vendredi 23 novembre 2018

Download link over random php image

I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link on top of the image?

Display random image from folder using PHP:

function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);

if($leading == '/')
{
    $directory = substr($directory, 1);
}
if($trailing != '/')
{
    $directory = $directory . '/';
}

if(empty($directory) or !is_dir($directory))
{
    die('Directory: ' . $directory . ' not found.');
}

$files = scandir($directory, 1);

$make_array = array();

foreach($files AS $id => $file)
{
    $info = pathinfo($dir . $file);

    $image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
    if(!in_array($info['extension'], $image_extensions))
    {
        unset($file);
    }
    else
    {
        $file = str_replace(' ', '%20', $file);
        $temp = array($id => $file);
        array_push($make_array, $temp);
    }
}

if(sizeof($make_array) == 0)
{
    die('No images in ' . $directory . ' Directory');
}

$total = count($make_array) - 1;

$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];

}

Markup:

echo "<img src=" . random_image('css/images/avatars') . " />";

I've tried looking around google for an answer but I can't find anything, any help would be appreciated




Aucun commentaire:

Enregistrer un commentaire