What is the best practice for implementing a download feature for webpage content in PHP?
To implement a download feature for webpage content in PHP, you can use the header() function to set the appropriate content type and headers for the file download. You should also read the file contents and output them to the browser. Additionally, you can use the readfile() function to simplify this process.
<?php
$file = 'example.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
?>
Related Questions
- What is the difference between printf and sprintf in terms of output in PHP?
- How can beginners in PHP and MySQL effectively handle the process of database creation and table setup without external tools like PHPmyAdmin?
- What are the potential pitfalls when transitioning from MySQL to MySQLi in PHP scripts?