これは、「php ダウンロード ハンドラ」で実行できます。
このようなメソッドを使用して、ファイルの内容とファイル情報ヘッダーをユーザーのブラウザーに返すことができますが、この前に他に何も出力されていないことを確認してください。
これを別のファイルに入れて、たとえばdownload.php
.
function returnFile( $filename ) {
// Check if file exists, if it is not here return false:
if ( !file_exists( $filename )) return false;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
// Suggest better filename for browser to use when saving file:
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
// Caching headers:
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
// This should be set:
header('Content-Length: ' . filesize($filename));
// Clean output buffer without sending it, alternatively you can do ob_end_clean(); to also turn off buffering.
ob_clean();
// And flush buffers, don't know actually why but php manual seems recommending it:
flush();
// Read file and output it's contents:
readfile( $filename );
// You need to exit after that or at least make sure that anything other is not echoed out:
exit;
}
基本的な使用のためにそれを拡張します:
// Added to download.php
if (isset($_GET['file'])) {
$filename = '/home/username/public_files/'.$_GET['file'];
returnFile( $filename );
}
警告:
$_GET
これは基本的な例であり、ユーザーが適切にサニタイズされていない悪意のある利点を利用しようとする可能性があることを考慮していません。
これは基本的に、passwd
特定の条件が適用される場合、ユーザーがファイルやその他の機密情報を取得できることを意味します。
たとえば、次のように取得し/etc/passwd
ます。
ブラウザをポイントするだけでhttp://server.com/download.php?file=../../../etc/passwd
、サーバーはそのファイルを返します。したがって、実際に使用する前に、ユーザーが提供する引数を適切にチェックしてサニタイズする方法を見つける必要があります。