Skip to content
Advertisement

Force download image from different server html

I have a link, that after click the link, user can download image. Right now, after click the link, user only can viewed the image.

How can I make browser to make after user click link, it will force to download the image

Here’s the code

<html>
   <head>
       <title> Download-Images</title>
  </head>
  <body>
    <p> Click the link ! You can download Image </p>
    <a download="logo.png" href="https://w3schools.com/images/myw3schoolsimage.jpg" title="Logo title" target="_blank">
    link
    </a>
  </body>
</html>

I’ve tried added php code from here and here in below my html code, but it’s not working.

Advertisement

Answer

You can try this. I have tested on my localhost and it worked.

html:

<html>
   <head>
       <title> Download-Images</title>
  </head>
  <body>
    <p> Click the link ! You can download Image </p>
    <a href="download.php?url=https://w3schools.com/images/myw3schoolsimage.jpg" title="Logo title">
    link
    </a>
  </body>
</html>

download.php

<?php
$url = $_GET['url'];
if ($url != '')
{
    $filename = end(explode('/', $url));
    $fileext = strtolower(end(explode('.', $filename)));
    
    if ($fileext == 'jpg' || $fileext == 'jpeg') { $type = 'image/jpeg'; }
    if ($fileext == 'png') { $type = 'image/png'; }
    if ($fileext == 'gif') { $type = 'image/gif'; }
    
    //$size = filesize($url);
    header("Content-Type: $type");
    header("Content-disposition: attachment; filename="" . $filename . """);
    header("Content-Transfer-Encoding: binary");
    //header("Content-Length: " . $size);
    readfile($url);
}else{
    echo 'url is blank';
}
?>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement