使用php下载图像链接

时间:2011-12-06 21:01:00

标签: php image download

我下载了此代码以用作下载按钮。

<?    
    $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; 
?> 

问题是,文件的名称以文件名中的整个路径结束,例如,此代码:

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

以名为“images_something.jpg”的图片结束

我想从最终文件名中删除“images_”,到目前为止我还没有运气。

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

basename()

$filename = basename($path);

P.S

多次设置Content-Type可能不是强制下载的最佳方式。另外,在您使用file_get_contents之前,我希望您正在清理$filename参数。

p.p.s

使用readfile,不要将其缓存在内存中。

答案 2 :(得分:2)

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

将您的文件名设置为只是基本名称?

除非您更改变量,否则不要在顶部执行此操作,因此您的路径仍可正常工作。