본문 바로가기
IT/PHP

22##]PHP로 홈페이지 만들기>파일 다운로드

by 혁이 2017. 4. 22.
반응형


안녕하세요


저번 업로드에 이어서 이번엔 다운로드를 구현해 보도록 하겠습니다.


먼저 downfile.php를 작성합니다.




downfile.php 

 

<?

ob_start();


$downfile=$_GET['file'];

$path='/files/'.$downfile;

if(file_exists($path) && is_file($path)){
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$downfile);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: '.filesize($path));
    ob_clean();
    flush();
    readfile($path);


}else{
    ?>
<script>
alert('파일이 없습니다.');
history.back();
</script>
<?
    
}
?>






네 이렇게 다운로드를 할 수 있는 페이지를 만들었습니다.

그럼 해당 페이지로 가기 위한 링크를 달아야 겠지요??

 read.php로 갑니다.




read.php 

 <tr>

        <td bgcolor=white colspan=4>
<font color=black>
<?
if($row['filename']){
?><div align=right>
<a href='downfile.php?file=<?=$row['filename']?>'><img src='file.png' width=20 height=20><?=$row['filename']?>
</a></div>
<?
}
?>
<pre><?=$row['comment']?></pre>
</font>
</td>
</tr>


read의 comment부분위에 삽입합니다.


파일이 있는경우 왼쪽 위에 파일사진과 파일명이 링크되어 있으며 클릭 시 다운로드를 할 수 있습니다.



저걸 클릭하면


이렇게 다운이 가능합니다.


파일이 없을시엔 이렇게 뜹니다.




반응형