简体   繁体   中英

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 display 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

You should save the image location in a variable then use it to create a link, plus display it.

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

or if you want to show the text link above, seperately then

$imageUrl = random_image('css/images/avatars');
echo "<a href=" . $imageUrl . ">Click Here</a><br />";
echo "<img src=" . $imageUrl . " />";

you could use simple javascript to do so, like onclick event for example :

just add this to img tag onclick='window.open('". random_image('css/images/avatars') ."')'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM