2017-04-02 19 views
0

に表示され、以下のコードをダウンロードしているが、この:PHP:強制ダウンロードが空のファイル

/home/my_site/www/wp-content/uploads/2017/03/2017-03-17-my_file.mp3 

私の知る限り、このパスは正しいです。しかし、私がechoをコメントアウトしてファイルをダウンロードすると、空のファイルになります。どうして?

コード:

if (isset($_GET['file'])) { 
    clearstatcache(); 
    $file_path = str_replace('http://www.example.com/', '', $_GET['file']); 
    $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path . '.mp3'; 
    echo $file_path; 

    if(file_exists($file_path)) { 
     $file_name = basename($file_path); 
     $file_size = filesize($file_path); 
     header("Cache-Control: private"); 
     header("Content-Type: application/stream"); 
     header("Content-Length: ".$file_size); 
     header("Content-Disposition: attachment; filename=".$file_name); 
     exit(); 
    } 
    else { 
     die('The provided file path is not valid.'); 
    } 
} 

EDIT:これは私がKIKOソフトウェアの提案の後に持っているものです。まだ空のファイルをダウンロードします。

$content = 'This is the content.'; 
$size = strlen($content); 
$name = 'test.txt'; 
header('Content-type: application/octet-stream'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: '.$size); 
header('Content-Disposition: attachment; filename='.$name); 
echo $content; 

はこれが最初の作品を確認してください:

<?php 
if (isset($_GET['file'])) { 
    $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['file'] . '.mp3'; 
    //echo $file_path; 
    //$file_path = $_SERVER['SCRIPT_FILENAME']; 
    if (file_exists($file_path)) { 
    $file_name = basename($file_path); 
    $file_size = filesize($file_path); 
    header('Content-type: application/octet-stream'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: '.$file_size); 
    header('Content-Disposition: attachment; filename='.$file_name); 
    //readfile($file_path); 
    exit(); 
    } 
    else { 
     die('The provided file path is not valid.'); 
    } 
} 
?> 

答えて

2

簡単な例では、ファイルをダウンロードします。そうでない場合は、ヘッダーに問題がある可能性があります。エラー報告を有効にして、次を参照してください。How to fix "Headers already sent" error in PHP

スクリプト自体をダウンロードして開始してください:

$file_path = $_SERVER['SCRIPT_FILENAME']; 
if (file_exists($file_path)) { 
    $file_name = basename($file_path); 
    $file_size = filesize($file_path); 
    header('Content-type: application/octet-stream'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: '.$file_size); 
    header('Content-Disposition: attachment; filename='.$file_name); 
    readfile($file_path); 
    exit(); 
} 
else { 
    die('The provided file path is not valid.'); 
}  

それ以降は、何か他のものをダウンロードしようとします。

問題を段階的に近づけると、どこが間違っているのかが分かりやすくなります。

+0

Firefoxがクラッシュし、ファイルがまったくダウンロードされていない場合... Chromeでは、ファイルの内容がわかりません。ファイルのダウンロードもありません。 – drake035

+0

私はあなたのコードをテストしなかったことを認めなければなりません。 'readfile()'は正しいので、あなたが持っている問題を引き起こしていません。あなたのヘッダーを少し変更しましたが、おそらくそれが助けになるでしょうか?彼らは標準的なものではなかった。また、URLを使用しているときは 'readfile()'のマニュアルも読んでください。 ** fopenラッパーが有効になっている場合は、この関数でURLをファイル名として使用できます。** –

+0

作業コードを提供したい場合は、https://stackoverflow.com/help/mcveも参照してください。 –

関連する問題