본문 바로가기
PHP/php

[PHP] 파일명 지정하여 파일 다운로드 소스코드

by 정쬬 2023. 9. 22.

PHP 파일 다운로드 기능을 만들기 위해서는 2개의 파일을 생성합니다.

file_down_form.php 파일을 선택하는 파일

file_down.php 실제 파일을 다운로드 해줄 파일

 

file_down_form.php 파일을 파일을 만들어 아래 내용을 복사해서 붙여놓습니다.

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	</head>
	<body>	
		<button type="submit" id="Send" onclick="location.href='file_down.php'">파일다운로드</button>
	<body>
</html>

 

두번째 파일 file_down.php을 만들어

<?
$file_loc = $_SERVER['DOCUMENT_ROOT']."/data/image.jpg; // 파일의 위치
$file_name = 'juho.jpg'; // 다운로드 받을 때 파일명

if($file_name && file_exists($file_loc)){

    Header("Content-type: application/octet-stream");
    Header("Content-Length: ".(string)(filesize($file_loc))); //다운로드 게이지를 나타냅니다.
    Header("Content-Disposition: attachment; filename=$file_name"); //파일을 무조건 다운로드 합니다.
    Header("Content-Transfer-Encoding: binary");
    Header("Pragma: no-cache");
    Header("Cache-Control: cache, must-revalidate"); //다운로드 확인창에서 다운로드 하지 않고 바로 열 수 있습니다.
    Header("Expires: 0");


    $fp = fopen($file_loc, "rb");
    while(!feof($fp)) {
        echo fread($fp, filesize($file_loc));
        flush();
    }
    fclose ($fp);
    exit;

}
else {
    ?>

    <script language="JavaScript">
        <!--
        alert("File not found.");
        history.back();
        //-->
    </script>

    <?
}
?>

해당 내용을 붙여놓습니다.

 

다음에는 파일 업로드 기능을 만들어 보겠습니다.

'PHP > php' 카테고리의 다른 글

PHP 문자열 함수모음(문자열 자르기 , 문자열 합치기)  (0) 2022.01.12