เขียนโปรแกรม สำหรับควบคุมการดาวน์โหลด ง่ายนิดเดียว
- roteee's blog
- 7 comments
- 1345 reads
// file: testDl.php
<?php
$mimeType = "image/jpeg";
$sourceFileName = "./zealot.jpg"
$destinationFileName = "zealot-from-phpzealots.jpg";
header("Content-type: ".$mimeType."");
header("Content-Disposition: attachment; filename=".$destinationFileName."");
echo file_get_contents($sourceFileName);
// ... and do something as you want such as keep the download stat for this file...
?>
เท่านี้ browser ก็จะขึ้น dialogbox สำหรับดาวน์โหลด แทนที่เราจะ link ไปหาไฟล์ตรงๆ

แต่บางครั้ง อาจจะใส่
header("Cache-Control: max-age=600");
header("Expires: ".date("r", mktime(0,0,0, date("m"),date("d")+7,date("Y")))."");
ไปด้วย เพื่อจัดการพวก Cache-Control ซึ่งเคยเจอปัญหาใน IIS ถ้าไม่ใส่ แบบนี้เข้าไป แล้วมีปัญหา เช่น Cache expired บ้าง ซึ่งคงเกี่ยวกับการ config ตัว IIS มั้ง แต่ผม config ไม่เป็น ก็เลยใส่ code ข้างต้นไว้ เพื่อแก้ปัญหา แต่บน Apache ไม่เคบพบปัญหาอะไร แต่อย่างไร