Я создал простой файловый менеджер, где пользователи могут загружать файлы любого типа, такие как файлы pdf, word или gif. Я хочу, чтобы все они загружали файл, а не просматривали его в браузерах. Загруженные имена файлов хранятся в базе данных.Force file download in php
ответ
Вы можете использовать заголовок "Content-Disposition" для этого:
header("Content-Disposition: attachment");
PHP manual является прекрасным примером для этого.
Обычно устанавливая Content-Disposition
на attachment
перед отправкой файла, загружайте браузер.
Вы либо необходимо настроить веб-сервер, чтобы обеспечить этот заголовок для файлов или отправить их самостоятельно с помощью PHP, посылая конкретный заголовок перед тем, как:
header('Content-Disposition: attachment; filename=your_file_name.pdf');
Берегитесь, что первое решение лучше, как вы выиграли Риск ваших загрузок сокращается, потому что время выполнения скрипта слишком велико (вы также можете его изменить).
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/pdf;\n");
$len = filesize($filename);
header("Content-Length: $len;\n");
header("Content-Disposition: attachment; filename=\"downfile.pdf\";\n\n");
echo readfile($filename)
Если вы хотите избежать кеширования, лучше использовать заголовок 'Cache-Control: no-cache'. Эти новые строки ('\ n') и'; 'не нужны. – Lekensteyn
исходный код взят из библиотеки TCPDF
// download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');
}
header('Content-Description: File Transfer');
if (headers_sent()) {
$this->Error('Some data has already been output to browser, can\'t send PDF file');
}
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// force download dialog
if (strpos(php_sapi_name(), 'cgi') === false) {
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);
header('Content-Type: application/pdf', false);
} else {
header('Content-Type: application/pdf');
}
// use the Content-Disposition header to supply a recommended filename
header('Content-Disposition: attachment; filename="'.basename($name).'";');
header('Content-Transfer-Encoding: binary');
$this->sendOutputData($this->getBuffer(), $this->bufferlen);
break;
в любом случае наиболее важной частью является
header('Content-Disposition: attachment; filename="'.basename($name).'";');
и заметить, что ребро al ;
внутри строки, без нее, это не сработает
- 1. Force file download in php не работает
- 2. Force file download header
- 3. PHP Force File Download Code - Ошибка
- 4. php force download headers
- 5. Force file download AND показать новую страницу
- 6. PHP force download
- 7. PHP force download не работает?
- 8. file download in spring mvc
- 9. PHP File Download
- 10. PHP file download header
- 11. PHP File Download Android
- 12. PHPExcel Force Download Issue
- 13. Idiot-proof, cross-browser force download in PHP
- 14. Force download in Google Chrome Extension
- 15. force download script
- 16. Force image download - .php files загрузить
- 17. Использование PHP force download для всех файлов
- 18. Force download не работает
- 19. PHP flat file download counter
- 20. php file force загрузить
- 21. PHP Force Download Causeing 0 Байт файлов
- 22. force pdf download on openshift с php
- 23. Force download image
- 24. PHP CSV create and force download
- 25. php force download script больше не работает
- 26. Force-downloading, from php file
- 27. Catch file download events in Electron app
- 28. Asynchronous file download in Cocos2d-x project
- 29. asp.net download excel file in IE6
- 30. User cancel file download in Grails
Возможный дубликат [Принудительно загрузить файл с помощью PHP] (http://stackoverflow.com/questions/1465573/forcing-to-download-a- file-using-php) – Randolpho
На этом сайте было задано несколько десятков или более раз. – Randolpho
Я прошу многоформатную загрузку, а не только PDF. Я бы хотел, чтобы пользователи загружали слова, excel, gif, а также – ktm