2014-04-21 12 views
0

안녕하세요, 저는 제품과 관련된 데모 파일을 다운로드 할 수있게하려고합니다. 내 코드는 내가Php force 다운로드 - 손상된 파일 다운로드

$ 데모하여 제품과 관련된 파일 이름을 얻을 수 있어요이

if(isset($_POST['submit'])){  
    $root = $_SERVER['DOCUMENT_ROOT']; 
    $path = "/download/"; 
    $path = $root.$path; 
$filename = $demo; 
$file = $path.$filename; 
header('Content-Type: application/force-download'); 
header("Content-Transfer-Encoding: Binary"); 
header("Content-Disposition: attachment; filename=\"".basename($file)."\";"); 
header("Content-Length: ".filesize($file)); 
readfile($file); 
    } 

처럼

사용자 후

자신의 정보를 제출, 다운로드가 자동으로 시작됩니다 . 이제는 존재하지 않는 파일이나 손상된 파일을 적절한 파일 이름으로 다운로드합니다. 도와주세요

답변

2
<?php 
$file = 'monkey.gif'; 

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 
    exit; 
} 

?> 

볼 수 있듯이 콘텐츠 유형은 application/octet-steam이며 의미 파일은 바이트 단위로 인코딩됩니다. 또한 캐시 헤더가 설정됩니다. 그런 다음 헤더는 강제로 ob_clean();flush()에 의해 전송됩니다. 파일을 읽습니다.

file_exists은 지정된 파일이 있는지 확인하기위한 것입니다. 또한 PHP 코드의 이름을 쉽게 쓰고 각 파일을 다운로드 할 수 있으므로 사용자 입력을 유도하지 않아야합니다. 그리고 파일의 이름에 심지어는 ../으로, 심지어 문서 또는 시스템 파일 등등.

+0

큰 도움이됩니다! @ 설정. 이것은 효과가 있었다. 자세한 답변을 주셔서 감사합니다. – Sanjeev