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

How to Force File Download in PHP?

DDD
DDDOriginal
2024-10-20 19:57:02508browse

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>
  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>
  3. Output the File:

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

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!

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