需求
在PHP開發中為了區分線上生產環境還是本地開發環境, 如果我們能通過判斷$_SERVER['RUNTIME_ENVIROMENT']為 'DEV'還是'PRO'來區分該多好, 可惜的是$_SERVER數組里面根本沒有RUNTIME_ENVIROMENT這個元素。
一、通過nginx的fastcgi_param來設置
在nginx配置文件中,可以在nginx總體的配置文件nginx.conf中,也可以在單獨的網站配置環境中進行設置,如:www.tomener.com.conf
在配置環境server段location中添加相應的配置信息:
location ~ \.php($|/) { try_files $uri =404; fastcgi_pass unix:/tmp/php-cgi.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param RUNTIME_ENVIROMENT 'PRO'; # PRO or DEV }
這里只添加了fastcgi_param RUNTIME_ENVIROMENT 'PRO'一個值,更多可以添加在后面
然后重啟重啟nginx
nginx -s reload
二、通過php主配置文件php-fpm.conf來設置
這個設置必須放在主配置文件php-fpm.conf里,不能放到include指令設置的子配置文件里,否則會報錯:「Array are not allowed in the global section」
我的php-fpm.conf位置在/usr/local/php/etc/php-fpm.conf
直接在配置文件中添加: env[RUNTIME_ENVIROMENT] = 'PRO' 添加后重啟php-fpm service restart php-fpm
通過上面2種方式添加$_SERVER變量值后,我們就可以直接在php文件中通過$_SERVER來獲取相應的變量值了。
不過據說配置信息通過nginx的fastcgi_param來設置的話,當nginx和php交互時,會帶來大量的數據傳輸。
Apache設置環境變量
SetEnv 變量名 變量值
<VirtualHost *:80> ServerAdmin webmaster@demo.com DocumentRoot "e:\wwwroot\demo" ServerName my.demo.com ErrorLog "logs/my.demo.com-error.log" CustomLog "logs/my.demo.com-access.log" common SetEnv RUNTIME_ENVIROMENT DEV <Directory "e:\wwwroot\demo"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost>