Как принудительно загрузить файл с помощью PHP

Я хочу потребовать, чтобы файл загружался при посещении пользователем веб-страницы с помощью PHP. Я думаю, что это как-то связано с file_get_contents, но не уверен, как это выполнить.

$url = "http://example.com/go.exe";

После загрузки файла с помощью header(location) он не перенаправляет на другую страницу. Он просто останавливается.

Комментарии к вопросу (2)

Прочитайте документацию о встроенной функции PHP readfile

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky)

Также не забудьте добавить соответствующий тип содержимого в зависимости от типа вашего файла application/zip, application/pdf и т.д. - но только если вы не хотите вызывать диалог сохранения.

Комментарии (5)
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

правильно

или лучше один для exe типа файлов

header("Location: $url");
Комментарии (5)
<?php
$file = "http://example.com/go.exe"; 

header("Content-Description: File Transfer"); 
header("Content-Type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"". basename($file) ."\""); 

readfile ($file);
exit(); 
?>

Или, когда файл не открывается браузером, можно просто использовать заголовок Location:

<?php header("Location: http://example.com/go.exe"); ?>
Комментарии (5)

Экран первый файл и установите его значение в URL-адрес.

index.php

<a href="download.php?download='.$row['file'].'" title="Download File">

download.php

<?php
/*db connectors*/
include('dbconfig.php');

/*function to set your files*/
function output_file($file, $name, $mime_type='')
{
    if(!is_readable($file)) die('File not found or inaccessible!');
    $size = filesize($file);
    $name = rawurldecode($name);
    $known_mime_types=array(
        "htm" => "text/html",
        "exe" => "application/octet-stream",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "jpg" => "image/jpg",
        "php" => "text/plain",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "gif" => "image/gif",
        "pdf" => "application/pdf",
        "txt" => "text/plain",
        "html"=> "text/html",
        "png" => "image/png",
        "jpeg"=> "image/jpg"
    );

    if($mime_type==''){
        $file_extension = strtolower(substr(strrchr($file,"."),1));
        if(array_key_exists($file_extension, $known_mime_types)){
            $mime_type=$known_mime_types[$file_extension];
        } else {
            $mime_type="application/force-download";
        };
    };
    @ob_end_clean();
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
    header('Content-Type: ' . $mime_type);
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');

    if(isset($_SERVER['HTTP_RANGE']))
    {
        list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
        list($range) = explode(",",$range,2);
        list($range, $range_end) = explode("-", $range);
        $range=intval($range);
        if(!$range_end) {
            $range_end=$size-1;
        } else {
            $range_end=intval($range_end);
        }

        $new_length = $range_end-$range+1;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range-$range_end/$size");
    } else {
        $new_length=$size;
        header("Content-Length: ".$size);
    }

    $chunksize = 1*(1024*1024);
    $bytes_send = 0;
    if ($file = fopen($file, 'r'))
    {
        if(isset($_SERVER['HTTP_RANGE']))
        fseek($file, $range);

        while(!feof($file) &&
            (!connection_aborted()) &&
            ($bytes_send
Комментарии (3)

В случае, если вам нужно загрузить файл с размером, превышающим допустимый предел памяти (memory_limit ini параметр), который приведет к в PHP фатальная ошибка: позволенный размер памяти ошибка 5242880 байт исчерпаны, вы можете сделать это:

// File to download.
$file = '/path/to/file';

// Maximum size of chunks (in bytes).
$maxRead = 1 * 1024 * 1024; // 1MB

// Give a nice name to your download.
$fileName = 'download_file.txt';

// Open a file in read mode.
$fh = fopen($file, 'r');

// These headers will force download on browser,
// and set the custom file name for the download, respectively.
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

// Run this until we have read the whole file.
// feof (eof means "end of file") returns `true` when the handler
// has reached the end of file.
while (!feof($fh)) {
    // Read and output the next chunk.
    echo fread($fh, $maxRead);

    // Flush the output buffer to free memory.
    ob_flush();
}

// Exit to make sure not to output anything else.
exit;
Комментарии (6)

Модификация принятый ответ выше, который также определяет MIME-тип в runtime:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: '.finfo_file($finfo, $path));

$finfo = finfo_open(FILEINFO_MIME_ENCODING);
header('Content-Transfer-Encoding: '.finfo_file($finfo, $path)); 

header('Content-disposition: attachment; filename="'.basename($path).'"'); 
readfile($path); // do the double-download-dance (dirty but worky)
Комментарии (0)

Следующий код является корректным способом реализации сервис загрузки в PHP, как описано в следующем учебник

header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=\"$file_name\"");
set_time_limit(0);
$file = @fopen($filePath, "rb");
while(!feof($file)) {
    print(@fread($file, 1024*8));
    ob_flush();
    flush();
}
Комментарии (2)

http://php.net/manual/en/function.readfile.php

<?в PHP файл $ = 'обезьяна.джиф';

если (file_exists($файл)) {

header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

header('Content-Disposition: attachment; filename='.basename($file));

header('Expires: 0');

header('Cache-Control: must-revalidate');

header('Pragma: public');

header('Content-Length: ' . filesize($file));

readfile($file);

exit;

}

?>

Что'ы все, что вам нужно. "у обезьян.джиф" и изменить имя файла. Если вам нужно скачать с другого сервера, то "обезьяна.гиф на" изменение "и http://www.exsample.com/go.exe"

Комментарии (1)

попробуйте это:

header('Content-type: audio/mp3'); 
header('Content-disposition: attachment; 
filename=“'.$trackname'”');                             
readfile('folder name /'.$trackname);          
exit();
Комментарии (0)

Вы можете скачать ручей, который будет потреблять значительно меньше ресурсов. пример:

$readableStream = fopen('test.zip', 'rb');
$writableStream = fopen('php://output', 'wb');

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip"');
stream_copy_to_stream($readableStream, $writableStream);
ob_flush();
flush();

В приведенном выше примере, я скачиваю test.zip (который фактически является Android-студия молнию на моей локальной машине). в PHP://output-это только для записи потока (обычно используется Echo или Print). после этого, вам нужно просто установить необходимые заголовки и назвать stream_copy_to_stream(источник, назначение). stream_copy_to_stream() метод действует как труба, которая принимает входные данные из потока источника (поток чтения) и трубы к потоку пункта назначения (запись стрима).

Комментарии (2)