简体   繁体   中英

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!

如果您需要没有文件夹名称的文件名部分,则必须使用basename($ filename) http://php.net/manual/en/function.basename.php

basename()

$filename = basename($path);

ps

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.

pps

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

$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.

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