How to Automatically Start a Download in PHP?
To automatically start a download in PHP, you can use the header()
function to send the appropriate headers to the browser indicating that a file download should begin. Here is an example of how to do this for a file named "example.txt":
<?php
header('Content-Disposition: attachment; filename="example.txt"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize('example.txt'));
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile('example.txt');
In this example, header()
is used to send several different headers to the browser. The first header, Content-Disposition
, specifies that the file should be downloaded with the specified filename. The second header, Content-Type
, specifies that the file is a binary file. The third header, Content-Length
, specifies the size of the file. The remaining headers set the file to be downloaded.
It is important to note that headers must be set before any other output is sent to the browser, so be sure to call these header() functions before any echo or print statements.