LoginSignup
4
3

More than 5 years have passed since last update.

CodeIgniterのコントローラを通しての画像出力がうまくいかない場合 (FW使う場合ありがちかも)

Posted at

画像のパスを直接見せたくないとかいう場合にたまにやる

PHPで普通にやるとこんな感じ

public funtion image() {
        header('Content-type: image/jpeg');
        readfile("/path/to/file");
}

CodeIgniter 使う場合は、こんな感じだとWebで見つけてやってみるも出ない

public funtion image() {
        $image_file = "/path/to/file";
        $this->output->set_content_type(get_mime_by_extension($image_file));
        $this->output->set_output(file_get_contents($image_file));
}

環境によるのかも知れませんが、最初はどっちでやっても
画像が壊れてるとか、文字になって出たりとか散々試行錯誤・・・

ブラウザでHTTPレスポンスヘッダを見ると text/html になってるし・・・
あ、昔、他のPHP FWこれでハマったことを思い出した。

ob_clean();

これです。
この関数は、出力バッファの内容を消去します。だそうです。

public funtion image() {
        ob_clean();  // ← 最初にやる
        $image_file = "/path/to/file";
        $this->output->set_content_type(get_mime_by_extension($image_file));
        $this->output->set_output(file_get_contents($image_file));
}

これで出ました。

ちなみにCodeIgniterの出力クラスのページには、そうしろという記述は何も無い。
画像のデータ出力する前に何かしら出てるとうまくいかないようです。

フレームワーク使うときにはありがちなのか、そうじゃないのかよくわからないけど
知ってると良いのかもしれない、もしくは常識なのか

4
3
1

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
4
3