Alperen Özdemir Alperen Özdemir - 19 days ago 7
PHP Question

Redirect To Start Download

I'm writing a php script. In download part I have to redirect an url to start download. However, when I click the button .jpg files are opened in the new tab. How can I convert it to download formation. Here is my php redirect code;

<?php

$url=@$_GET['url'];

function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location=\''.$url.'\';</script‌​>');
}else{
header('Location: ' . $url);
die();
}
}

redirect($url);

?>

Answer

Multiple solutions to download...

Like a download button:

<a target="_blank" download="download" href="http://www.w3schools.com/css/trolltunga.jpg">Test</a>

You could also do a file_get_contents of the file in PHP and serve it with the appropriate headers like here:

how to download a file from file_get_contents?

But not quite via a redirect, unless the source contains the appropriate headers. There's always the button hack as shown here:

Download image with JavaScript

Any of these suit your needs?