Home Backend Development PHP Tutorial Complete list of PHP file download functions: analysis of file download examples of readfile, header, Content-Disposition and other functions

Complete list of PHP file download functions: analysis of file download examples of readfile, header, Content-Disposition and other functions

Nov 18, 2023 pm 03:26 PM
header Download Document readfile content-disposition

Complete list of PHP file download functions: analysis of file download examples of readfile, header, Content-Disposition and other functions

Comprehensive list of PHP file download functions: file download example analysis of readfile, header, Content-Disposition and other functions

File downloading is an essential function in Web applications One, and PHP, as a widely used Web development language, provides a variety of functions and methods for file downloading.

This article will introduce commonly used file download functions in PHP, including readfile, header, Content-Disposition, etc., and show corresponding code examples to help everyone better understand and master the implementation of file downloading.

1. readfile() function

The readfile() function is one of the most commonly used file download functions in PHP. It is used to read files and send them to the output stream. The following is a basic syntax example of using the readfile() function to download a file:

$file = 'example.txt';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
Copy after login

The above code first checks whether the file exists, then sets various parameters of the output stream, and finally uses the readfile() function to read and send the file. into the output stream. The advantage of using the readfile() function is that it is convenient and fast, and the amount of code is small. But the disadvantages are also obvious. This function will read the entire file into the memory at one time and then send it. If the file is too large, it may cause a server performance bottleneck.

2. Header() function

The header() function can be used to send HTTP headers. It is usually used in conjunction with the readfile() function to implement file downloading. The header() function can set various HTTP headers, including Content-Type, Content-Disposition, Content-Length, etc.

The following is an example of using the header() function and the readfile() function to implement file downloading:

$file = 'example.txt';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
Copy after login

The above code is similar to the previous example code, the only difference is that ob_clean( ) and flush() functions. The ob_clean() function can clear the output buffer to ensure that response headers can be sent correctly. The flush() function can force all output to be sent to the client.

3. Content-Disposition

Content-Disposition is an HTTP header used to indicate how to handle the transmitted data, such as whether to download the file as an "attachment". By setting the Content-Disposition header we can specify the name of the file when downloading.

The following is an example of using the Content-Disposition header to implement file download:

$file = 'example.txt';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="example.txt"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
Copy after login

Compared with the previous sample code, this time we specify the file name in the Content-Disposition header , without using the basename() function to extract the file name from the file path. It should be noted that the quotes in filename="example.txt" are required, otherwise the browser may cause parsing errors when the file name contains spaces.

Other Notes

When using the file download function, we also need to pay attention to the following points:

1. The file path must be a relative path or an absolute path, not URL, otherwise the download will fail.

2. When using the header() function to set the HTTP header, it must be called before outputting any content.

3. Adding ob_clean() and flush() functions can avoid the problem of failure to send certain response headers.

4. If the downloaded file is very large, you should consider downloading in segments or using other download optimization methods.

Summary

PHP file download functions mainly include readfile, header, Content-Disposition, etc. Using these functions can quickly and easily implement the file download function, but you need to pay attention to issues such as file paths, HTTP header settings, buffer cleaning, etc. to ensure that the download can proceed normally. For large files, download performance and efficiency issues also need to be considered.

The above is the detailed content of Complete list of PHP file download functions: analysis of file download examples of readfile, header, Content-Disposition and other functions. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python opening operation after downloading the file Python opening operation after downloading the file Apr 03, 2024 pm 03:39 PM

Python provides the following options to open downloaded files: open() function: open the file using the specified path and mode (such as 'r', 'w', 'a'). Requests library: Use its download() method to automatically assign a name and open the file directly. Pathlib library: Use write_bytes() and read_text() methods to write and read file contents.

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use PHP functions to upload and download attachments for sending and receiving emails? How to use PHP functions to upload and download attachments for sending and receiving emails? Jul 25, 2023 pm 08:17 PM

How to use PHP functions to upload and download attachments for sending and receiving emails? With the rapid development of modern communication technology, email has become an important way for people to communicate and transmit information in daily life. In web development, we often encounter the need to send and receive emails with attachments. As a powerful server-side scripting language, PHP provides a wealth of functions and class libraries that can simplify the email processing process. This article will introduce how to use PHP functions to upload and download attachments for sending and receiving emails. Email is sent first, we

How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

How does SpringBoot pass parameters in the Header through Feign calls? How does SpringBoot pass parameters in the Header through Feign calls? May 16, 2023 pm 08:38 PM

[SpringBoot] Passing parameters in the Header through Feign calls How to pass Header parameters through Feign Problem description When we use Feign to request the Api interface of another service in Spring Cloud, there is a need to pass the parameters in the Header. If no special processing is done, it will The parameters in the Header will be lost. Solution 1: Pass it through @RequestHeader(name="headerName"). For example: Feign is defined as follows @FeignClient(name="service-name")pub

How to trigger file download when clicking HTML button or JavaScript? How to trigger file download when clicking HTML button or JavaScript? Sep 12, 2023 pm 12:49 PM

Nowadays, many applications allow users to upload and download files. For example, plagiarism detection tools allow users to upload a document file that contains some text. It then checks for plagiarism and generates a report that users can download. Everyone knows how to use inputtypefile to create a file upload button, but few developers know how to use JavaScript/JQuery to create a file download button. This tutorial will teach you various ways to trigger a file download when an HTML button or JavaScript is clicked. Use HTML's <a> tag and download attribute to trigger file download when the button is clicked. Whenever we give the <a> tag

What does linux header mean? What does linux header mean? Jul 18, 2023 pm 03:34 PM

The Linux header refers to the beginning of a file or data stream, which is used to contain metadata about the content. By correctly writing and using Header files, developers can better utilize system resources and improve code readability and Maintainability.

How to use Hyperf framework for file downloading How to use Hyperf framework for file downloading Oct 21, 2023 am 08:23 AM

How to use the Hyperf framework for file downloading Introduction: File downloading is a common requirement when developing web applications using the Hyperf framework. This article will introduce how to use the Hyperf framework for file downloading, including specific code examples. 1. Preparation Before starting, make sure you have installed the Hyperf framework and successfully created a Hyperf application. 2. Create a file download controller First, we need to create a controller to handle file download requests. Open the terminal and enter

See all articles