为什么此代码返回“”:
$ip = "";
if(getenv("HTTP_CLIENT_IP"))
{
$ip = getenv("HTTP_CLIENT_IP");
} elseif(getenv("HTTP_X_FORWARDED_FOR")) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
} else {
$ip = getenv("REMOTE_ADDR");
}
环境:W2003EE,IIS 6.0,PHP 5.2.9(ISAPI)
$ _ SERVER是一个内置的PHP变量。 getenv()着眼于当前 环境。
在我的情况下,我需要使用$ _SERVER。谢谢大家!
答案 0 :(得分:1)
尝试$ _SERVER ['REMOTE_ADDR']或$ _SERVER ['HTTP_X_FORWARDED_FOR']
如果您想知道设置了什么,可以在某处转储$ _SERVER。
答案 1 :(得分:0)
环境变量REMOTE_ADDR的值必须为空或未设置。如果在linux上工作,请通过echo $ REMOTE_ADDR命令检查终端上的值。如果返回null,则在分配$ ip之前设置其值。
答案 2 :(得分:0)
问题可能与IIS工作方式有所不同。我在CakePHP项目中使用这两个函数取得了成功。
/**
* Gets remote client IP
*
* @return string Client IP address
* @access public
*/
function getClientIP($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} else {
if (env('HTTP_CLIENT_IP') != null) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
}
if (env('HTTP_CLIENTADDRESS') != null) {
$tmpipaddr = env('HTTP_CLIENTADDRESS');
if (!empty($tmpipaddr)) {
$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
}
}
return trim($ipaddr);
}
/**
* Gets an environment variable from available sources, and provides emulation
* for unsupported or inconsistent environment variables (i.e. DOCUMENT_ROOT on
* IIS, or SCRIPT_NAME in CGI mode). Also exposes some additional custom
* environment information.
*
* @param string $key Environment variable name.
* @return string Environment variable setting.
* @link http://book.cakephp.org/view/701/env
*/
function env($key) {
if ($key == 'HTTPS') {
if (isset($_SERVER['HTTPS'])) {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
return (strpos(env('SCRIPT_URI'), 'https://') === 0);
}
if ($key == 'SCRIPT_NAME') {
if (env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) {
$key = 'SCRIPT_URL';
}
}
$val = null;
if (isset($_SERVER[$key])) {
$val = $_SERVER[$key];
} elseif (isset($_ENV[$key])) {
$val = $_ENV[$key];
} elseif (getenv($key) !== false) {
$val = getenv($key);
}
if ($key === 'REMOTE_ADDR' && $val === env('SERVER_ADDR')) {
$addr = env('HTTP_PC_REMOTE_ADDR');
if ($addr !== null) {
$val = $addr;
}
}
if ($val !== null) {
return $val;
}
switch ($key) {
case 'SCRIPT_FILENAME':
if (defined('SERVER_IIS') && SERVER_IIS === true) {
return str_replace('\\\\', '\\', env('PATH_TRANSLATED'));
}
break;
case 'DOCUMENT_ROOT':
$name = env('SCRIPT_NAME');
$filename = env('SCRIPT_FILENAME');
$offset = 0;
if (!strpos($name, '.php')) {
$offset = 4;
}
return substr($filename, 0, strlen($filename) - (strlen($name) + $offset));
break;
case 'PHP_SELF':
return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME'));
break;
case 'CGI_MODE':
return (PHP_SAPI === 'cgi');
break;
case 'HTTP_BASE':
$host = env('HTTP_HOST');
if (substr_count($host, '.') !== 1) {
return preg_replace('/^([^.])*/i', null, env('HTTP_HOST'));
}
return '.' . $host;
break;
}
return null;
}