เทคนิค การเขียน PHP
Php code download file เขียนphpทำระบบดาวน์โหลดไฟล์ เช่น ไฟล์ .exe, zip
ตัวอย่างทำเป็นไฟล์ ชื่อ download.php เก็บไฟล์ไว้ที folder tmp และรับค่า filename ผ่านทาง url โค้ดก็จะเช็คว่าไฟล์ที่จะดาวน์โหลดว่าเป็นชนิดใด และอ่านข้อมูลไฟล์ แล้วกำหนด header บอกให้ browser ทราบว่าเป็นไฟล์ชนิดใด การนำไปใช้่อาจเพิ่มโค้ดเก็บสถิติการโหลดเก็บข้อมูลลง sql เพิ่มก็ได้
<?php $path = 'tmp'; $filename = $path .'/'.$_GET['filename']; $filename = realpath($filename); $file_extension = strtolower(substr(strrchr($filename,"."),1)); switch ($file_extension) { case "pdf": $ctype="application/pdf"; break; case "exe": $ctype="application/octet-stream"; break; case "zip": $ctype="application/zip"; break; case "doc": $ctype="application/msword"; break; case "xls": $ctype="application/vnd.ms-excel"; break; case "ppt": $ctype="application/vnd.ms-powerpoint"; break; case "gif": $ctype="image/gif"; break; case "png": $ctype="image/png"; break; case "jpe": case "jpeg": case "jpg": $ctype="image/jpg"; break; default: $ctype="application/force-download"; } if (!file_exists($filename)) { die("NO FILE HERE"); } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: $ctype"); header("Content-Disposition: attachment; filename="".basename($filename)."";"); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".@filesize($filename)); set_time_limit(0); @readfile("$filename") or die("File not found.");
?>
|
|
เขียนโดย mindphp
วันศุกร์ที่ 12 กุมภาพันธ์ 2010 เวลา 11:13 น.