dongyi2534 2012-09-27 20:28
浏览 86
已采纳

通过readfile()保护/提供文件,强行下载?

I'm trying to make a simple script that does two things:

  1. Serves up a file and hide's it's destination
  2. Has a download counter

Now, I'm doing this in the wordpress environment, but this question isn't completely wordpress-related so I figured I would ask here.

Basically, the way I have it set up, currently, is I have a link that when you click it sets a $_['GET'] which is then checked if is set. If it is set, the download file is served.

the link: <a href="http://localhost:8888/fresh/?dl_id=01">Click here!</a>'

the $_['GET'] code: http://pastebin.com/93nD43gA

There is a bit of wordpress jargon in the code, but basically it's checking a download count user_meta and if it's > 0, serveFile() is called.

The main problem I'm having here is, if I click the link, readfile() loads the actual file contents INTO the window (garbled text). If I add a target=_blank to the <a> it opens a new browser window and loads the contents INTO the window.

This approach seemed to work perfectly fine when I was doing it as stand-alone php files. My main issue is that I need to keep the wordpress space so I can call functions, etc. associated with it.

I have tried using the $_['GET'] on both the self page, another page with a custom template (the code in the pastebin above), and as a stand-alone php file. Both the first two options load the file INTO the window. The third doesn't preserve wordpress functions, even if I include blog-header.php.

Can anyone point me in to the right direction of how to get the file to force download and not load INTO the window?

  • 写回答

2条回答 默认 最新

  • dsgo31121 2012-09-27 20:31
    关注

    You need to set the appropriate header for whatever the file type is. For example, if readfile always serves, PDFs, it should be done like this:

    // disable browser caching -- the server may be doing this on its own
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    
    header('Content-Type: application/pdf');
    //forces a download
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=filename.pdf');
    readfile($file);
    

    Keep in mind that header only works if you have not sent any data in the request at all including whitespace.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算