0

I am able to select and display the images, but i need it to display as link and then download it on the click of link

$imagesDirectory =basename("images/"); //path to directory

if (is_dir($imagesDirectory))
{
    $opendirectory = opendir($imagesDirectory); // to read images from path

    while (($image = readdir($opendirectory)) !== false)
    {
        if(($image == '.') || ($image == '..'))
        {
         continue;
        }

        $imgFileType = pathinfo($image,PATHINFO_EXTENSION);

        if(($imgFileType == 'jpg') || ($imgFileType == 'png')) //Types of files
        {
            echo "<img src='images/".$image."' width='200'> ";
        }
    }

    closedir($opendirectory);
 }
?>
zeenath
  • 27
  • 4
  • Add `echo "Download` for each image? If you want to force download the image, then change the URL to something like `download.php?img=$image` instead and read https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php about how to force download. – M. Eriksson May 30 '18 at 05:56
  • Visit this url. you can find your answer here. https://stackoverflow.com/questions/2408146/href-image-link-download-on-click – F5 Buddy May 30 '18 at 06:09

1 Answers1

0

You're very close to the answer, just wrap the image in anchor tag and pass "download" attribute to it. that's it:

$imagesDirectory =basename("images/"); //path to directory

if (is_dir($imagesDirectory))
{
    $opendirectory = opendir($imagesDirectory); // to read images from path

    while (($image = readdir($opendirectory)) !== false)
    {
        if(($image == '.') || ($image == '..'))
        {
         continue;
        }

        $imgFileType = pathinfo($image,PATHINFO_EXTENSION);

        if(($imgFileType == 'jpg') || ($imgFileType == 'png')) //Types of files
        {
            /*xxxxxxxxxxxx-----Here's the Change-----xxxxxxxxxxxx*/
            echo "<a href='images/".$image."' download><img src='images/".$image."' width='200'> </a>";
        }
    }

    closedir($opendirectory);
 }
?>
Rajnish
  • 123
  • 8