Home >Backend Development >PHP Tutorial >How to Force File Downloads in PHP Without Redirecting to the Browser?

How to Force File Downloads in PHP Without Redirecting to the Browser?

DDD
DDDOriginal
2024-10-20 20:02:301013browse

How to Force File Downloads in PHP Without Redirecting to the Browser?

Generating Download Links in PHP

Introduction

Providing users with the ability to download files is a common feature in web applications. This article will guide you through creating download links for images and preventing navigation to the browser.

Solution

To force a file download, you can utilize the following code:

<code class="php"><?php
    // File path on disk
    $filePath = '/path/to/file/on/disk.jpg';

    // Check if file exists
    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);
        
        // Output file
        readfile ($filePath);
        exit();
    } else {
        die('Invalid file path');
    }
?></code>

By using this code snippet at the beginning of a PHP page, users will be able to download a file by clicking a normal link.

Security Considerations

When creating a function for downloading arbitrary files, it's crucial to safeguard against malicious input. Employ measures such as realpath to prevent directory traversal and restrict downloads to predetermined locations to maintain website security.

The above is the detailed content of How to Force File Downloads in PHP Without Redirecting to the Browser?. 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