Download file in PHP
When developing a website or application, we often need to implement the file download function, which can be easily implemented through PHP. This article will introduce how to use PHP to implement the file download function.
1. File download process
Before downloading the file, we need to understand the download process:
- The user clicks the download button on the web page or application;
- The server accepts the download request;
- The server checks user permissions and file existence;
- The server sends the file to the user;
- The user receives the file and saves it .
2. Prepare to download the file
In PHP, we can use the readfile function to read the file content and output it to the browser. However, we need to make sure the file exists, otherwise an exception will be thrown. The following is a simple code example:
$file_path = '/path/to/your/file/yourfile.extension'; if (file_exists($file_path)) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file_path)); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($file_path)); readfile($file_path); exit; } else { die('File not found.'); }
In the above code, we first use the file_exists function to check whether the file exists. If the file exists, set the HTTP header file to tell the browser that a file is about to be downloaded, and in the Content Specify the file name in -Disposition, specify the file type in Content-Type, and use the readfile function to output the file content.
3. Prevent file downloads from being stolen links
Due to the nature of the browser, some unscrupulous sites may steal your files, so we need to prevent file downloads from being stolen links.
We can add the following code to prevent file downloads from being stolen:
$referer = $_SERVER['HTTP_REFERER']; if ($referer && !preg_match('/^https?://' . $_SERVER['SERVER_NAME'] . '/', $referer)) { header("HTTP/1.1 403 Forbidden"); die("Access denied."); }
This code will check the HTTP_REFERER header information and ensure that it matches the domain name of the current server. If it does not match, it will return 403 Status code, access prohibited.
4. Implement segmented download
When downloading larger files, you may need to implement segmented download function to speed up the download speed and reduce network bandwidth usage. With the help of HTTP 1.1's Range header information, we can easily implement segmented downloads.
The following is a sample code:
$file_path = '/path/to/your/file/yourfile.extension'; if (file_exists($file_path)) { $size = filesize($file_path); $start = 0; $end = $size - 1; if (isset($_SERVER['HTTP_RANGE'])) { if (preg_match('/bytes=h*(d+)-(d*)[D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) { $start = intval($matches[1]); if (!empty($matches[2])) { $end = intval($matches[2]); } } } if ($start > $end || $end > $size - 1 || $start < 0) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header("Content-Range: bytes $start-$end/$size"); exit; } header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file_path)); header('Content-Transfer-Encoding: binary'); header("Content-Range: bytes $start-$end/$size"); header('Accept-Ranges: bytes'); header('Content-Length: ' . ($end - $start + 1)); header("Cache-control: private"); header('Pragma: private'); header('Expires: ' . gmdate('D, d M Y H:i:s T', time() + 3600)); $fp = fopen($file_path, 'rb'); fseek($fp, $start); $buffer_size = 1024 * 8; //每次读取8 KB $bytes_send = 0; while (!feof($fp) && ($bytes_send < $end - $start + 1)) { $buffer = fread($fp, $buffer_size); echo $buffer; flush(); $bytes_send += strlen($buffer); } fclose($fp); exit; } else { die('File not found.'); }
In the above code, we first check the HTTP_RANGE header information. If the header information does not exist, the entire file is output. If the header information exists, the start offset and end offset are parsed, then the fseek function is used to locate the file pointer, and the fread function is used to read the file content and output it to the browser.
5. Conclusion
It is not difficult to implement the file download function in PHP. We only need to check whether the file exists and set the correct HTTP header information. Using HTTP 1.1 Range header information can easily achieve segmented downloads, and preventing file downloads from stolen links can protect the security of files. Therefore, we can choose to implement the required functions according to our needs to achieve a better user experience.
The above is the detailed content of Download file in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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

How to implement file upload and download in PHP back-end function development? In web development, file upload and download are very common functions. Whether users upload images, documents or download files, back-end code is required to process them. This article will introduce how to implement file upload and download functions on the PHP backend, and attach specific code examples. 1. File upload File upload refers to transferring files from the local computer to the server. PHP provides a wealth of functions and classes to implement file upload functions. Create HTML form first, in HTM

CakePHP middleware: realizing file upload and download functions. With the development of the Internet, file upload and download functions are becoming more and more common. When developing web applications, we often need to implement file upload and download. When developing applications using the CakePHP framework, middleware is a very useful tool that can help us simplify the code and implement file upload and download functions. Next, I will introduce how to use CakePHP middleware to implement file upload and download functions. First, we need to create a new
