Wednesday, October 15, 2008

แสดงไฟล์ pdf ด้วย php

เดี๋ยวนี้ทำพวก coding เยอะ
อย่างเช่นตัวอย่างนี้ เหตุเกิดเพราะว่า จะมีการเรียก pdf ไฟล์จากเครื่อง server อีกเครื่องหนึ่ง โดยที่ไม่ต้องการให้ผู้เรียกใช้งานรู้ว่า file pdf มาจากไหน ก็เลยส่งเป็น request มาให้ เช่น

/searchResearchContent.php?NewsID=12121212&key=12121311AABDDD00

แล้วให้เราส่งเป็น ไฟล์ pdf ออกมา  วิธีการก็ง่าย ๆ แค่ ต้องเข้าใจ Header ก็พอ

-- php --
$filename = "38_file.pdf"; 
header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header('Content-disposition: attachment; filename='.basename($filename)); 
header("Content-Type: application/pdf"); 
header("Content-Transfer-Encoding: binary"); 
header('Content-Length: '. filesize($filename)); 
readfile($filename);
-- php --

ในกรณีที่ต้องการให้แสดง pdf ใน Browser ก็แค่เปลี่ยนจาก "Content-disposition: attachment;" เป็น "Content-disposition: inline;" เท่านั้นเอง

1 comment:

Anonymous said...

ขอบคุณมากเลยคร่า อย่างน้อยมันก็ดาวน์โหลดมาได้ละ อ้างอิงกับ Chrome คร่า แต่ IE ยังไม่ลองเลยคร่า