[英]Create variable on one conttoller (CI)
我想問些什么,所以我想做可變的ip,像這樣的代碼
if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
}
但是我的問題是我想將該變量$ip
用於控制器(一個文件控制器)上的所有公共函數,我該如何做?
注意:我使用類似CodeIgniter的框架。
嘗試這個:
<?php
class MyController extends CI_Controller
{
protected $ip;
public function __construct()
{
parent::__construct(); //just added this, sorry
if (!empty($_SERVER["HTTP_CLIENT_IP"])){
//check for ip from share internet
$this->ip = $_SERVER["HTTP_CLIENT_IP"];
} elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
// Check for the Proxy User
$this->ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
$this->ip = $_SERVER["REMOTE_ADDR"];
}
}
public function index()
{
echo 'Your IP is '.$this->ip;
}
public function myMethod()
{
//you can use $this->ip in here too
}
}
訪問http://host/path/to/CI/mycontroller/index
以查看輸出
如果需要,可以更改$ip
的可見性
將其放在控制器的構造函數中。
https://www.codeigniter.com/userguide3/general/controllers.html#class-constructors
<?php
class Yourconstructor extends CI_Controller {
public function __construct()
{
parent::__construct();
private $ip;
if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$this->ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$this->ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$this->ip = $_SERVER["REMOTE_ADDR"];
}
}
}
public function index() {
if ($this->ip == $some_var_posted_or_whatever) {
// do something here...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.