Send File to the User
When a user interacts with a PHP script, you may encounter scenarios where you need to transmit a file, such as a PDF, to the client's browser. To achieve this, the appropriate approach depends on the storage location of the file.
Server-Side File
Assuming the file resides on the server, the preferred method is to utilize the readfile() function. However, merely executing readfile($file) is insufficient. The script must include appropriate headers to enable the client to receive the file successfully.
Refer to the following example from the official PHP manual:
<?php $file = 'monkey.gif'; if (file_exists($file)) { 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)); ob_clean(); flush(); readfile($file); exit; } ?>
The above is the detailed content of How to Send Files to Users from a PHP Server?. For more information, please follow other related articles on the PHP Chinese website!