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.
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":
Example of automatically starting a download in PHP
<?php
if (headers_sent()) {
die('Headers already sent');
}
header('Content-Disposition: attachment; filename="example.txt"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize('example.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile('example.txt');
exit;
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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 contains arbitrary binary data. The third header, Content-Length, specifies the size of the file. The remaining headers (Expires, Cache-Control, Pragma) instruct the browser and intermediate caches to prevent caching the response, ensuring the download starts immediately.
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.