When visiting web pages, browsers often open images or files directly—for example, Chrome by default does so. However, in some cases, we want users to download images or files directly when clicking a link rather than viewing them in the browser. The key to achieving this is setting the HTTP response header Content-Disposition. This article shows how to use PHP to modify response headers to force image downloads in browsers.
Use PHP’s header function to set the response header that instructs the browser to treat the file as an attachment and specify the download filename:
<span class="fun">header('Content-Disposition: attachment; filename="filename.jpg"');</span>
Here, Content-Disposition defines the download behavior, and filename specifies the name the user will save the file as. You can replace it with the actual filename.
Use file_get_contents() to read the file content and output it with echo. A complete example:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="filename.jpg"');
echo file_get_contents('path/to/filename.jpg');
The Content-Type: application/octet-stream tells the browser to handle the download as a binary stream, ensuring the file is saved as an attachment.
Here is a full PHP code example demonstrating how to set response headers and output the file to enforce download:
// File path
$filepath = 'path/to/filename.jpg';
// Get file MIME type
$filetype = mime_content_type($filepath);
// Get filename
$filename = basename($filepath);
// Set response headers
header('Content-Type: ' . $filetype);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filepath));
// Read and output file content
echo file_get_contents($filepath);
?>
In web development, setting the Content-Disposition header allows control over whether users download a file directly rather than preview it in the browser. This is very useful for PDFs, images, and other file types, effectively improving user experience and file management convenience.
This article introduced how to use PHP to modify HTTP response headers to force file downloads. Simply setting Content-Disposition and the appropriate content type can achieve the desired effect. Developers can flexibly adjust according to their needs to enhance website interaction.