LoginSignup
9

More than 5 years have passed since last update.

header() でリダイレクトさせるあとはだいたい exit() しよう

Posted at

header() 関数を用いて、リダイレクト処理を行うことはよくあります。

<?php

header('Location: /');
exit();

で、例えば以下のように、ユーザ認証を行って、妥当であれば、メールを送信するという場合。

ここで header は早期 return ぎみに使っています。だけど、header でリダイレクトをしたからといって、それ以降の処理を行わないわけではありません。以下のコードでは、validate_user の戻り値にかかわらず、send_mail_to_user が実行されます。

<?php

if (validate_user($user)) {
    header('Location: /');
}

send_mail_to_user($user)

なので

exit を加えます。exit はスクリプトの終了。これでバリデーションが通らない場合は、send_mail_to_user が実行されません。

<?php

if (validate_user($user)) {
    header('Location: /');
    exit();
}

send_mail_to_user($user)

たしかに

header って ステータスコード変えたりするし、渡してるの文字列だし、Location: からはじまるときだけ、以降を実行しないっていうのは気持ち悪かったりするので、今の仕様で納得だな、という感じ。

exit() つけよう

参考

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
9