LoginSignup
3
0

More than 3 years have passed since last update.

【PHP】Mixed Content(混合コンテンツ)が起きた際の対処法

Last updated at Posted at 2020-07-03

■概要

ステージング環境から本番環境にデプロイした際、ページがHTTP表記になっており、
かつデベロッパーツールのコンソールにエラーが出ていた。
確認すると、
Mixed Content: The page at 'https://test.com/test/' was loaded over HTTPS, but requested an insecure url 'http://test.com/test/'. This content should also be served over HTTPS.

■原因

ステージング環境ではSSL対応をしていないため、
PHPで表示中のサイトURLを取得する方法がHTTPのままになっていた。
それにより、ブラウザからこのページに安全ではないURLが含まれているとアラートが出されていた。

■対処法

始めは修正前の書き方をしていたので、プロトコルを変更すれば解決するが、
ステージングと本番環境によって出し分ける方法を取った方がコードとしてもきれいだと思い、
URLの取得方法を変えてみた。

修正前
<?php echo esc_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])?>

修正後
<?php echo esc_url( (empty($_SERVER["HTTPS"]) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>

修正内容

三項演算子を使い、HTTPとHTTPSでの接続を条件分岐しています。
分かりやすくif文を使った場合、下記のようになります。

if (empty($_SERVER["HTTPS"])) {
  echo "http://";
} else {
  echo "https://";
}

■参考サイト

3
0
2

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