【PHP】ファイル名を変えてダウンロード

ブラウザ上でダウンロードするファイル名を変更するお話

WordPressを使ってECサイトを作成するというのはたまに聞きますが、今回はECサイト管理に特化したCMS「EC-CUBE」の改修です。

管理画面からダウンロードするファイルが既存の関数を使用していまして、ID+拡張子というなんとも味気なく管理しにくいので変更したいとのことでした。

スポンサーリンク

headerで出力

要件としてはユーザ名+日付のファイル名にしたいとのこと。

元の処理を見るとごにょごにょとurlを設定する処理が流れて最後に下記で出力しています。

header("Location: $url");
exit;

シンプルな構成ですがとりあえずコメントアウトしておきます。

ファイル名を変えてダウンロードするためにreadfileを使います。

下記は参考サイト

How to Force download a File in PHP
In this tutorial, you will learn how to use the PHP readfile() function to force download a file with an optional download rate.

「Content-Disposition: attachment;」でファイル名を設定します。

readfileでファイルを読み込むことで別名でダウンロードが可能になります。

$file = 'failename.txt';
$username = get_username($uid); /* 名前取得する処理 */
$filename = $username.'_'.date('Ymd',strtotime($cdate)).'.txt';
if (file_exists($file)) {
	header('Content-Description: File Transfer');
	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename='.$filename);
	header('Expires: 0');
	header('Cache-Control: must-revalidate');
	header('Pragma: public');
	header('Content-Length: '.filesize($file));
	readfile($file);
	exit();
}

EC-CUBEは初めてさわりましたが、カスタマイズが大変そうだなと感じました。

バージョンによって扱いがかなり変わるようなので勉強しておきたいと思います。

コメント

タイトルとURLをコピーしました