L
L
Lorem Ipsum2020-05-15 15:08:39
PHP
Lorem Ipsum, 2020-05-15 15:08:39

How to download a file using php?

In general, it is necessary in the PHP code, when a certain condition is triggered, to start downloading the file. How can this be implemented?

By downloading a file, I mean:
Display a dialog box for downloading a file to the visitor's computer in the browser of the site visitor (or if automatic download is set in his browser, download the file to the visitor's device)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
ynChrome, 2020-05-15
@ImpAnonym

It's a very simple magic (:

<?php
// Имя файла
$fileName = 'path/to/file/1.m4a';

// Посылаем заголовки
header("Content-Type: audio/mp4");
header("Content-Length: " . filesize($fileName));

// Если нужен диалог сохранения, добавляем такой заголовок:
$quoted = sprintf('"%s"', addcslashes(basename($fileName), '"\\'));  // Или любое другое имя файла
header("Content-Disposition: attachment; filename='$quoted'");


// Можно использовать хэндлер файла
$fp = fopen($fileName, 'rb');
fpassthru($fp);

// А можно без хэндлера
readfile($fileName);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question