yii2_自定义Component
Posted 木子炜培先生
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了yii2_自定义Component相关的知识,希望对你有一定的参考价值。
1
namespace common\components; use Yii; use yii\base\Component; class ReadHttpHeader extends Component { public function RealIP() { $ip = false; $seq = array(‘HTTP_CLIENT_IP‘, ‘HTTP_X_FORWARDED_FOR‘ , ‘HTTP_X_FORWARDED‘ , ‘HTTP_X_CLUSTER_CLIENT_IP‘ , ‘HTTP_FORWARDED_FOR‘ , ‘HTTP_FORWARDED‘ , ‘REMOTE_ADDR‘); foreach ($seq as $key) { if (array_key_exists($key, $_SERVER) === true) { foreach (explode(‘,‘, $_SERVER[$key]) as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP) !== false) { return $ip; } } } } } }
2在common/config/main-local.php
// 新添加的 ‘ReadHttpHeader‘ => [ ‘class‘ => ‘common\components\ReadHttpHeader‘ ],
3调用自定义组件backend\controllers\SiteController.php
public function actionIndex() { //自定义组件 echo Yii::$app->ReadHttpHeader->RealIP(); return $this->render(‘index‘); }
以上是关于yii2_自定义Component的主要内容,如果未能解决你的问题,请参考以下文章