How can PHP be used to initiate a file download upon button click?
To initiate a file download upon button click in PHP, you can use the header() function to set the appropriate content type and headers. You will need to specify the file path and name in the headers to trigger the download prompt in the browser when the button is clicked.
<?php
if(isset($_POST['download_button'])){
$file = 'path/to/your/file.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
<form method="post">
<button type="submit" name="download_button">Download File</button>
</form>
Related Questions
- What are some best practices for efficiently managing language lists in PHP for web development?
- What are the common pitfalls when trying to establish a connection to an Oracle database using oci8 in PHP?
- What are the considerations when concatenating variables with user input in PHP to avoid errors or security vulnerabilities?