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

How Can I Use PHP to Send Files to Users?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 16:53:10229browse

How Can I Use PHP to Send Files to Users?

File Transmission to Users via PHP Script

PHP scripts offer the capability to send files to users upon request. When encountering a scenario where you possess a PDF file stored on disk, you can effectively transmit it to the user.

Utilizing readfile()

To facilitate file transmission, PHP provides the readfile() function. This function plays a crucial role in outputting files. Simply invoking readfile($file) may not suffice. To ensure a successful file delivery, it is essential to define appropriate headers.

Header Definition:

PHP allows you to define headers to configure how data is sent and received. In the context of file transmission, these headers dictate the behavior of the client receiving the file.

Refer to the following example from the official PHP manual for an illustration of how to implement headers for file transmission:

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

Additional Notes:

  • Ensure the file is available at the specified server path.
  • Define the appropriate content type for the file being sent, such as 'application/pdf' for PDF files.
  • Set the Content-Disposition header to trigger a download dialogue in the user's browser.
  • Configure caching and expiration headers to prevent the client from caching the file unnecessarily.

The above is the detailed content of How Can I Use PHP to Send Files to Users?. 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