[PHP] 파일과 텍스트 다운로드 함수

맨날 만들어 쓰기 귀찮아서 제일 시간 많이 들여 만든 걸 갖다 놓는다.

/**
 * Download file from path and mimetype.
 *
 * @param      $path
 * @param      $mimetype
 * @param null $filename
 */
function download_file ($path, $mimetype, $filename = NULL) {
    if (empty($filename)) {
        $filename = pathinfo($path, PATHINFO_BASENAME);
    }

    if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
        $filename = rawurlencode($filename);
    }

    header('cache-control: no-cache');
    header("Content-Type: $mimetype");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Length: " . filesize($path));
    readfile($path);
}

/**
 * Download text file from string.
 *
 * @param $filename
 * @param $string
 */
function download_txt($filename, $string){
    header('cache-control: no-cache');
    header('Content-Type: text/plain');
    header("Content-Disposition: attachment; filename={$filename}");
    header("Content-Length: " . strlen($string));
    echo $string;
}

gist 링크

카테고리

17년차 풀스택 웹 개발자 Mytory입니다

웹 개발에서도 중요한 것은 개념입니다.
이 블로그에는 제가 개발하며 익힌 개념들을 정리합니다.

워드프레스를 오래 다뤄 왔고 강의도 두 편 찍었습니다.
– 인프런 “워드프레스 제대로 개발하기 어드민 편, 클라이언트 편
– 클래스101 “누구나 할 수 있는 워드프레스 홈페이지 만들기 – 기획부터 출시까지 한 방에 OK

유튜브 채널에 워드프레스 관련 팁들을 올리고 있습니다.

👉 소개 더 보기

대표글

댓글 남기기