How to Send Files to Users from a PHP Server?

Linda Hamilton
Release: 2024-11-25 08:13:48
Original
198 people have browsed it

How to Send Files to Users from a PHP Server?

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;
}
?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template