Home >Backend Development >PHP Tutorial >How Can I Efficiently Send Files to Users Using PHP?

How Can I Efficiently Send Files to Users Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 22:55:12883browse

How Can I Efficiently Send Files to Users Using PHP?

Sending Files to Users with PHP

When users request a file from a PHP script, efficiently delivering it becomes crucial. Here's how to do it effectively:

Using readfile()

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;
}

Configuring Headers

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!

Statement:
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