PHP 헤더 및 파일 처리를 사용하여 파일 다운로드를 강제하는 방법은 무엇입니까?

Linda Hamilton
풀어 주다: 2024-10-20 20:00:30
원래의
589명이 탐색했습니다.

How to Force File Downloads Using PHP Headers and File Handling?

PHP에서 강제로 파일 다운로드

사용자가 웹사이트에서 이미지나 기타 파일을 다운로드하도록 허용하는 것은 일반적인 요구 사항입니다. PHP에서는 적절한 헤더와 파일 처리 기술을 활용하여 이 작업을 수행할 수 있습니다.

헤더 조작

파일을 강제로 다운로드하려면 적절한 헤더를 브라우저. 이러한 헤더는 브라우저 동작을 제어하고 파일을 브라우저 창에 표시하는 대신 파일을 다운로드하도록 지시합니다. 일부 필수 헤더에는 다음이 포함됩니다.

<code class="php">header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);  // File size in bytes
header("Content-Disposition: attachment; filename=".$fileName);  // File name to display</code>
로그인 후 복사

파일 출력

헤더가 올바르게 설정되면 파일 자체를 출력해야 합니다. 이는 파일 데이터를 읽어 브라우저로 보내는 PHP readfile() 함수를 사용하여 수행됩니다.

<code class="php">readfile ($filePath);                   
exit();</code>
로그인 후 복사

코드 예

모두 정리 , 다음은 PHP에서 이미지 다운로드를 강제하는 예제 스크립트입니다:

<code class="php"><?php
    // Fetch the file info.
    $filePath = '/path/to/file/on/disk.jpg';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?></code>
로그인 후 복사

다운로드 패널 생성

파일을 즉시 다운로드하는 대신 패널을 선호하는 경우 사용자 확인을 위해 표시되도록 하려면 스크립트를 약간 수정하면 됩니다. 예는 다음과 같습니다.

<code class="html"><a href="download.php?file=/path/to/file.jpg">Download</a></code>
로그인 후 복사

download.php에서 실제 파일 다운로드를 시작하는 버튼이 있는 확인 패널을 표시할 수 있습니다.

<code class="php"><?php
    $file = $_GET['file'];

    if(file_exists($file)) {
        // Display confirmation panel...
        if(isset($_POST['confirm'])) {  // Confirm button clicked
            header("Cache-Control: private");
            header("Content-Type: application/stream");
            header("Content-Length: ".filesize($file));
            header("Content-Disposition: attachment; filename=".basename($file));

            readfile ($file);                   
            exit();
        }
    }
    else {
        die('Invalid file path.');
    }
?></code>
로그인 후 복사

이 접근 방식을 사용하면 다음을 제공할 수 있습니다. 더욱 사용자 친화적인 다운로드 메커니즘을 제공합니다.

위 내용은 PHP 헤더 및 파일 처리를 사용하여 파일 다운로드를 강제하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!