Home >Backend Development >PHP Tutorial >How Can I Efficiently Send Files to Users Using PHP?
When users request a file from a PHP script, efficiently delivering it becomes crucial. Here's how to do it effectively:
The PHP function readfile() provides a straightforward way to send files to users. It reads the file from the server and outputs it to the browser.
Syntax:
readfile($file);
Example:
$file = 'myfile.pdf'; if (file_exists($file)) { readfile($file); exit; }
To ensure the file is delivered correctly, it's important to configure appropriate HTTP headers. By default, readfile() sends the file as inline instead of prompting the browser to download it.
header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file));
These headers specify the file's description, type, disposition (attachment or inline), transfer encoding, and other crucial information for proper file downloading.
By combining readfile() with appropriate header configuration, you can efficiently send PDF or other files to users upon their request.
The above is the detailed content of How Can I Efficiently Send Files to Users Using PHP?. For more information, please follow other related articles on the PHP Chinese website!