2014-09-25 60 views
-1

今天,我想創建一些PHP腳本,它將直接強制下載mp3文件。無法通過php腳本訪問文件

文件我想下載放入聲音文件夾中,我可以通過http://playall.pl/sounds/ThemadpixprojectBadChick.mp3

訪問,但是當它涉及到PHP腳本 - 函數file_exists說,這個文件是不是此服務器上。

我該如何解決?使用它來下載文件

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file_name)); 
    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; 

而獲得的文件名和文件的URL

$file_name = ''.$sound['Sounds']['artist'].' - '.$sound['Sounds']['title'].'.mp3'; 

$file_name = preg_replace('/\s+/', '_', $file_name); 

$file = 'http://playall.pl'.$this->webroot.'sounds/'.$sound['Sounds']['src_url']; 
+0

爲什麼你不重定向瀏覽器? – 2014-09-25 23:25:51

+0

因爲我想強制按鈕單擊下載此文件。 – GamaPL 2014-09-25 23:28:38

+0

並添加,即時通訊使用CakePHP框架。 – GamaPL 2014-09-25 23:29:09

回答

0

對於file_exists($file)$file需要的完整路徑變量

代碼IM。並且必須是文件系統上的路徑,而不是Web位置的網址。

所以,你需要這樣的東西:

$file = $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/sounds/'; 

$_SERVER['DOCUMENT_ROOT']爲您提供了文件系統路徑到你的htdocs文件夾,那麼剩下的需要是從那裏相對的。

0

好的。問題很簡單 - 我在路徑前有一個/。現在它工作正常。感謝所有的幫助!