문제

링크를 방문할 때 브라우저가 자동으로 로컬 컴퓨터에 파일을 다운로드하도록 하려면 PHP에 어떤 코드를 추가해야 합니까?

특히 소프트웨어 이름을 클릭하면 사용자에게 파일을 디스크에 저장하라는 메시지를 표시하는 다운로드 사이트와 유사한 기능을 생각하고 있습니까?

도움이 되었습니까?

해결책

파일을 출력하기 전에 다음 헤더를 보내십시오.

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom:'application/octet-stream' MIME 유형에 관심이 있습니다.저는 그런 사실을 몰랐고 항상 '응용 프로그램/강제 다운로드'를 사용했습니다. :)

다른 팁

다음은 PDF를 다시 보내는 예입니다.

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);

@쳐서 자르다 다른 작업을 수행할 수 있는 응용 프로그램/강제 다운로드 콘텐츠 유형을 찾지 못했습니다(IE 및 Firefox에서 테스트).실제 MIME 유형을 다시 보내지 않는 이유가 있습니까?

PHP 매뉴얼에도 있습니다 헤일리 왓슨 게시됨:

파일을 렌더링하는 대신 강제로 다운로드하고 저장하려면 "application/force-download"와 같은 MIME 유형이 없다는 점을 기억하세요.이 상황에서 사용할 올바른 유형은 "application/octet-stream"이며, 다른 것을 사용하는 것은 단지 클라이언트가 인식할 수 없는 MIME 유형을 무시하고 대신 "application/octet-stream"을 사용해야 한다는 사실에 의존하는 것입니다(참조:RFC 2046의 섹션 4.1.4 및 4.5.1).

또한 따르면 IANA 등록된 애플리케이션/강제다운로드 유형이 없습니다.

깨끗한 예입니다.

<?php
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename="example.txt"');
    header("Content-Length: " . filesize("example.txt"));

    $fp = fopen("example.txt", "r");
    fpassthru($fp);
    fclose($fp);
?>

내 코드는 txt,doc,docx,pdf,ppt,pptx,jpg,png,zip 확장명에서 작동하며 실제 MIME 유형을 명시적으로 사용하는 것이 더 낫다고 생각합니다.

$file_name = "a.txt";

// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);

header('Content-disposition: attachment; filename='.$file_name);

if(strtolower($ext) == "txt")
{
    header('Content-type: text/plain'); // works for txt only
}
else
{
    header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top