Re: [請益] 下載檔案的問題
※ 引述《rollman (死命咬著牙...)》之銘言:
: <html>
: <head>
: </head>
: <body>
: <form name="form1" method="post" action="test.php">
: <select name="column1" size=1 >
: <option value="Select">請選擇</option>
: <option value="WDD051001.pdf">WDD1</option>
: <option value="WDD051101.pdf">WDD2</option>
: </select>
: <input name="submit" type="submit" value="Ok">
: </form>
: <?
: $file_name = $_POST["column1"];
: $file_url = rawurlencode($file_name);
: header("Content-Type: application/download");
: header("Content-Disposition: attachment; filename=$file_name");
: readfile($file_url);
: ?>
: </body>
: </html>
若你的 pdf 不是以 binary 存在資料庫中,而是在某資料夾,
那應不需要用這麼複雜的方式--直接提供 LINK 就好了。
若因某種原因堅持用這方式,ok
我認為你 header 的處理方式有點怪。基本上在傳送 header 之前,
不能有其他輸出。因為 header 的意義是在定義『之後』的 http 資
料流是屬何種型態。若已先輸出了 html ,那麼之後的所有檔案都會
被認定屬於 html 型態。是故,照你這麼做,理當該得到 warning ?
(有可能因為當掉了所以沒能看到 ^^")
我建議的處理方式是,將 pdf 的輸出另外寫個 php 管理。亦即將引
述的 php code 放進 pdf.php。檔案名稱可以 GET 傳入,
例:pdf.php?filename=WDD051001.pdf
這一來這 pdf.php 輸出的內容,才是真的 pdf。你原先的程式碼是將
PDF 的 raw data 硬塞進 html 當中,我猜可能是這個原因才使 Browser 當掉
pdf.php 的 header 最好包含下列三個資訊:
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$filename");
你的程式碼中漏了 Content-length,此外 Content-type 似乎與 pdf 的型態不符。
Content-length 可以讓瀏覽器比較能預估正確的下載時間、以及結束點;
而 Content-type 的設定上, pdf 應為 application/pdf。 若想知道其他的 type
請參考 MIME 的相關資料。
另外補充一點,上述的方法或許可以解決問題,但是安全上有所疑慮。
特別是 pdf.php?filename=WDD051001.pdf 這段。若要稍微改進一些安全性,
那麼最好將 .pdf 附檔名的部分放進程式;或者將檔名作特殊的處理,例如:
用 HASH 映射檔名。直接用外部變數指定檔名,可能藏有資安問題。
--
「640K ought to be enough for anybody.!」
- Bill Gates -
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.119.199.121
※ 編輯: foxzgerald 來自: 140.119.199.121 (11/29 17:05)
討論串 (同標題文章)
PHP 近期熱門文章
PTT數位生活區 即時熱門文章