Felipe Gaona Reydet
Felipe Gaona Reydet

Reputation: 31

Download Image link using php

I downloaded this code to use as a download button.

<?    
    $filename = $_GET["filename"];
    $buffer = file_get_contents($filename);

    /* Force download dialog... */
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    /* Don't allow caching... */
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    /* Set data type, size and filename */
    header("Content-Type: application/octet-stream");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . strlen($buffer));
    header("Content-Disposition: attachment; filename=$filename");

    /* Send our file... */
    echo $buffer; 
?> 

The thing is, the name of the file ends up with the whole path in the file name, for example, this code:

<a href="download.php?filename=images/something.jpg">

Ends up with an image named "images_something.jpg"

I'd like to remove the "images_" from the final file name, so far I haven't had any luck.

Thanks for the help!

Upvotes: 3

Views: 4394

Answers (3)

mikevoermans
mikevoermans

Reputation: 4007

$filename = basename($filename); 
header("Content-Disposition: attachment; filename=$filename");

Set your filename to only be the basename?

Don't do it at the top unless you change the variables though so your pathing to it still works.

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101614

basename()

$filename = basename($path);

p.s

Setting Content-Type several times may not be the best way to force a download. Also, I hope you're sanitizing that $filename argument before you use a file_get_contents.

p.p.s

Use readfile, don't cache it in the memory.

Upvotes: 2

InuYaksa
InuYaksa

Reputation: 726

If you need the file name part without folder name, you have to use basename($filename) http://php.net/manual/en/function.basename.php

Upvotes: 3

Related Questions