LoginSignup
2
6

More than 5 years have passed since last update.

CakePHP2の $this->response でファイルをダウンロードさせるときのIEファイル名文字化け解消

Last updated at Posted at 2016-05-21

CakePHP2の $this->response でファイルをダウンロードさせるときのIEファイル名文字化け解消

やりたいこと:PHPでファイルをダウンロードさせたい

CakePHP2でファイルをダウンロードさせる.公式から以下のようにすれば良いことがわかる.

download.php
public function sendFile($id) {
    $file = $this->Attachment->getFile($id);
    $this->response->file($file['path']);
    // レスポンスオブジェクトを返すとコントローラがビューの描画を中止します
    return $this->response;
}

参照:http://book.cakephp.org/2.0/ja/controllers/request-response.html

問題

IEでダウンロードするとファイル名に文字化けが起こる.
色々なサイトから,通常のPHPでは以下のようにすれば良いことがわかる.

download.php
header("Content-Type: application/octet-stream;");
header("Content-Disposition: attachment; filename="ファイル名"; filename*=UTF-8''URLエンコーディングされたファイル名);
echo file_get_contents("ファイル名");

参照:http://www.negimiso.net/blog/2015/06/19/%E3%83%80%E3%82%A6%E3%83%B3%E3%83%AD%E3%83%BC%E3%83%89%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D%E3%80%81%E6%96%87%E5%AD%97%E5%8C%96%E3%81%91%E3%81%A8%E3%81%AE%E6%A0%BC%E9%97%98/

CakePHP2ではどうすればよいのか?

download.php
public function sendFile($id) {
    $file = $this->Attachment->getFile($id);
    $content = 'attachment;';
    $content .= 'filename='.$filename;
    $content .= 'filename*=UTF-8\'\''.rawurlencode($filename); 
    $this->response->header('Content-Disposition', $content);
    $this->response->file($file['path']);
    // レスポンスオブジェクトを返すとコントローラがビューの描画を中止します
    return $this->response;
}

無事IEでもファイル名が文字化けせずダウンロードできた.

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6