お問い合わせのフォーム制作の際に、こんなエラー文を目にした方もいると思います。
Warning: Cannot modify header information…
これは様々な原因があります。
今からご紹介するのはその原因と、対策対処法をお伝えしようと思います。
その① header()関数の前に改行や余白、出力がある
<?php
echo 'エコー';
header('Location: https://ryoheiobayashi.com/');
?>
<?php
//空白、改行
header('Location: https://ryoheiobayashi.com/');
?>
上記の記述だと「Warning: Cannot modify header information…」が発生する。
<?php
header('Location: https://ryoheiobayashi.com/');
echo 'エコー';
?>
この記述で「Warning: Cannot modify header information…」のエラーが消えます。
その② php.iniのoutput_bufferingをoffからonにする
output_buffering = Off
から
output_buffering = ON
に変更するだけ。
その③ ob_start();にする
<?php
ob_start();
?>
この一文を入れるだけです。
ちなみに私が愛用しているTransmitMail(https://github.com/dounokouno/TransmitMail)という無料テンプレートフォームも
たまにindex.phpに対してheaderとfooterをincludeした状態で色々書くと「Warning: Cannot modify header information…」のエラーが起きます。
なので私は③の方法を使って対応いたしました。
<?php
ob_start();
require_once '../TransmitMail/lib/TransmitMail.php';
$tm = new TransmitMail();
$tm->init('config/config.php');
include '../common/header.php';
$tm->run();
include '../common/footer.php';
?>
まとめ
Warning: Cannot modify header information…は、かなり厄介なエラーなので、あまりサーバー周りを弄らないコーダーやマークアップエンジニア、フロントエンドエンジニアなどの方は是非、このエラーには注意してください!!
参考URL
・Warning: Cannot modify header information – headers already sent by
・「Warning: Cannot modify header information…」エラーの解決方法[PHP]