0
0

More than 1 year has passed since last update.

PHPでの実行環境を環境変数で切り替える

Last updated at Posted at 2022-01-07

PHPで実行環境毎に環境を切り替えたい

切り替えるにはどうするか。色々方法はあるかとおもいます。
おおきく以下かなとおもいます。

  • ローカル環境の場合
  • 開発サーバー環境の場合
  • ステージングサーバー環境の場合
  • 本番環境の場合

で、PHPで以下で取得するとよさそうですが、

$_SERVER["HTTP_HOST"]

これが良さそうだけど、環境によっては取得できない場合がある。

確実に取得するには、ウェブサーバーに値を設定すればよい。確実にその値が取得できる。

忘れがちなので環境をコピーしたときに、チェック!

###nginx

xxx.conf
location ~ \.php$ {
いろいろ設定
    fastcgi_param PROD_STG_ENV production;

  }

###apache

xxx.conf
<VirtualHost *:80>

   SetEnv PROD_STG_ENV production
</VirtualHost>

## PHPで環境変数を取得する

apacheやnginxでの設定を取得し、環境を切り替える

<?php
if (getenv('PROD_STG_ENV') === 'production') {
    // 本番での設定
}else if (getenv('PROD_STG_ENV') === 'develop') {
    // 開発サーバーでの設定
}else if (getenv('PROD_STG_ENV') === 'staging') {
    // ステージングサーバーでの設定
} else {
    // ローカルでの設定
}
0
0
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
0
0