2017-04-14 1 views
0

서버의 "노래"라는 디렉토리에있는 사용자 컴퓨터에 MP3 파일을 다운로드하려고합니다. 나는이 파일들을 브라우저를 통해 다운로드하는 스크립트를 실행할 수 있었다. 그러나 이러한 파일은 확장명이 .mp3 인 텍스트로 다운로드됩니다. 나는이 파일들이 서버에서 다운로드 할 때 재생 가능한 mp3 파일이되기를 바란다.PHP 서버의 디렉토리에서 MP3 파일을 다운로드하십시오.

여기 내 PHP 스크립트입니다.

<?php 

$link = mysqli_connect("...","...","....","...") or die("Error ".mysqli_error($link)); 

if(mysqli_connect_errno()) 
{echo nl2br("Failed to connect to MySQL:". mysqli_connect_error() . "\n");} 
else 
{echo nl2br("Established Database Connection \n");} 
스크립트는 현재 모든 노래의 목록을 다운로드합니다 //

여기?>

내가 얻을 결과의 예입니다 서버

$target = "songs/"; 


if ($handle = opendir($target)) { 
    while (false !== ($entry = readdir($handle))) { 
     if ($entry != "." && $entry != "..") { 
      echo $entry."'>".$entry."</a>\n"; 
     } 
    } 
    closedir($handle); 
} 


$file = basename($_GET['file']); 
$file = 'Songs_From_Server'.$file; 

if(!$file){ // file does not exist 
    die('file not found'); 
} else { 


    header("Cache-Control: private"); 
    header("Content-type: audio/mpeg3"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Disposition: attachment; filename=".basename($file)); 


    readfile($file); 

}에서 발견 txt 파일. , header()echo, print_r, 어떤을 포함 모든 출력 전에 전송해야 1983 년

설립 데이터베이스 연결
01 그는 1983 년 '> 01 Fly.mp3하기 위해 사랑 그는

+0

정확한 위치 MP3 파일은 무엇입니까? 'readfile ($ file);'을 호출하기 전에'print $ file; 그것은 무엇을 말하는가? – user4035

+0

readfile을 호출하기 전에 $ file을 인쇄하려고했습니다. 다운로드가 동일한 결과를 반환합니다. 이상하게 보입니다. @ user4035 – gsanchez

+0

MP3 파일은 대상을 만든 서버의 "노래"라는 디렉토리에 있습니다. @ user4035 – gsanchez

답변

1

먼저 Fly.mp3하기 위해 사랑 html, 시작 태그 앞에 공백 (예 : <?php). ~ the manual

둘째, 파일 내용을 브라우저에 응답하려면 스크립트에서 다른 내용을 출력해서는 안됩니다. 컨텐츠 이외의 출력은 컨텐츠의 일부로 간주됩니다. 멀티 파트로 보내지 않으면 클라이언트에서 처리 할 수 ​​있습니다. 그래서

, 예를 들어

<?php 

$fileName = $_GET['file']; 
$path = '/directory/contains/mp3/'; 
$file = $path.$fileName 

if (!file_exists($file)) { 
    http_response_code(404); 
    die(); 
} 

header("Cache-Control: private"); 
header("Content-type: audio/mpeg3"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Disposition: attachment; filename=".$fileName); 
//So the browser can display the download progress correctly 
header("Content-Length: ".filesize($file); 

readfile($file); 
관련 문제