Home > Backend Development > PHP Tutorial > How to Force File Download in PHP?

How to Force File Download in PHP?

DDD
Release: 2024-10-20 19:57:02
Original
615 people have browsed it

How to Force File Download in PHP?

Force File Download in PHP

To provide a download link for a file in PHP, you can use the following steps:

  1. Retrieve the File Information:

    <code class="php">$filePath = '/path/to/file/on/disk.jpg';
    
    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);
    } else {
        die('The provided file path is not valid.');
    }</code>
    Copy after login
  2. Output Headers:

    <code class="php">header("Cache-Control: private");
    header("Content-Type: application/stream");
    header("Content-Length: ".$fileSize);
    header("Content-Disposition: attachment; filename=".$fileName);</code>
    Copy after login
  3. Output the File:

    <code class="php">readfile ($filePath);                   
    exit();</code>
    Copy after login

Note: Be cautious if implementing this in a function to allow downloads of arbitrary files, as you need to prevent directory traversal and restrict downloads to a defined area.

The above is the detailed content of How to Force File Download in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template