如何检测用户是否在 PHP 中的本地主机上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2053245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect if the user is on localhost in PHP?
提问by Richie Marquez
In other words, how can I tell if the person using my web application is on the server it resides on? If I remember correctly, PHPMyAdmin does something like this for security reasons.
换句话说,我如何知道使用我的 Web 应用程序的人是否在它所在的服务器上?如果我没记错的话,PHPMyAdmin 出于安全原因会做这样的事情。
回答by mauris
You can also use $_SERVER['REMOTE_ADDR']for which IP address of the client requesting is given by the web server.
您还可以使用$_SERVER['REMOTE_ADDR']Web 服务器提供的客户端请求的 IP 地址。
$whitelist = array(
'127.0.0.1',
'::1'
);
if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
// not valid
}
回答by Jens T?rnell
As a complement, as a function...
作为补充,作为一个功能......
function isLocalhost($whitelist = ['127.0.0.1', '::1']) {
return in_array($_SERVER['REMOTE_ADDR'], $whitelist);
}
回答by reekogi
Newer OS users (Win 7, 8) may also find it necessary to include an IPV6-format remote address in their whitelist array:
较新的操作系统用户(Win 7、8)也可能会发现有必要在他们的白名单数组中包含一个 IPV6 格式的远程地址:
$whitelist = array('127.0.0.1', "::1");
if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
// not valid
}
回答by Pekka
$_SERVER["REMOTE_ADDR"]should tell you the user's IP. It's spoofable, though.
$_SERVER["REMOTE_ADDR"]应该告诉你用户的IP。不过,它是可以欺骗的。
Check this bounty questionfor a very detailed discussion.
检查这个赏金问题以获得非常详细的讨论。
I think what you remember with PHPMyAdmin is something different: Many MySQL Servers are configured so that they can only be accessed from localhost for security reasons.
我认为您对 PHPMyAdmin 的记忆有所不同:许多 MySQL 服务器被配置为出于安全原因只能从本地主机访问它们。
回答by nicola
It doesn't seem you should use $_SERVER['HTTP_HOST'], because this is the value in http header, easily faked.
似乎您不应该使用$_SERVER['HTTP_HOST'],因为这是 http 标头中的值,很容易伪造。
You may use $_SERVER["REMOTE_ADDR"]too, this is the more secure value, but it is also possible to fake. This remote_addris the address where Apache returns result to.
您也可以使用$_SERVER["REMOTE_ADDR"],这是更安全的值,但也可能是伪造的。这remote_addr是Apache返回结果的地址。
回答by Daniklad
I'm sorry but all these answers seem terrible to me. I would suggest rephrasing the question because in a sense all machines are "localhost".
我很抱歉,但所有这些答案对我来说似乎都很糟糕。我建议重新表述这个问题,因为从某种意义上说,所有机器都是“本地主机”。
The question should be; How do I run different code paths depending on which machine it is executed on.
问题应该是;如何根据在哪台机器上执行不同的代码路径来运行不同的代码路径。
In my opinion, the easiest way is to create a file called DEVMACHINE or whatever you want really and then simply check
在我看来,最简单的方法是创建一个名为 DEVMACHINE 或任何你真正想要的文件,然后简单地检查
file_exists('DEVMACHINE')
file_exists('DEVMACHINE')
Remember to exclude this file when uploading to the live hosting environment!
上传到实时托管环境时,请记住排除此文件!
This solution is not depending on network configuration, it can not be spoofed and makes it easy to switch between running "live-code" and "dev-code".
这个解决方案不依赖于网络配置,它不能被欺骗,并且可以很容易地在运行“live-code”和“dev-code”之间切换。
回答by Eugen Wesseloh
How about to compare $_SERVER['SERVER_ADDR'] === $_SERVER['REMOTE_ADDR']to determine if client is on the same machine as server?
如何比较$_SERVER['SERVER_ADDR'] === $_SERVER['REMOTE_ADDR']以确定客户端是否与服务器在同一台机器上?
回答by Heroselohim
If you want to have a whitelist / allowlistthat supports static IPsand dynamic names.
如果您想要一个支持静态 IP和动态名称的白名单/许可名单。
For example:
例如:
$whitelist = array("localhost", "127.0.0.1", "devel-pc.ds.com", "liveserver.com");
if (!isIPWhitelisted($whitelist)) die();
This way you could set a list of names/IPsthat will be able (for sure) to be detected. Dynamic names add more flexibility for accessing from different points.
通过这种方式,您可以设置能够(肯定)被检测到的名称/IP列表。动态名称为从不同点访问增加了更大的灵活性。
You have two common options here, you could set a name in your local hosts fileor you could just use one dynamic name providerthat could be found anywhere.
这里有两个常用选项,您可以在本地主机文件中设置一个名称,或者您可以只使用一个可以在任何地方找到的动态名称提供程序。
This function CACHES results because gethostbyname is a very slow function.
这个函数缓存结果是因为 gethostbyname 是一个非常慢的函数。
For this pupose I've implemented this function:
为此目的,我实现了这个功能:
function isIPWhitelisted($whitelist = false)
{
if ( isset($_SESSION) && isset($_SESSION['isipallowed']) )
{ return $_SESSION['isipallowed']; }
// This is the whitelist
$ipchecklist = array("localhost", "127.0.0.1", "::1");
if ($whitelist) $ipchecklist = $whitelist;
$iplist = false;
$isipallowed = false;
$filename = "resolved-ip-list.txt";
$filename = substr(md5($filename), 0, 8)."_".$filename; // Just a spoon of security or just remove this line
if (file_exists($filename))
{
// If cache file has less than 1 day old use it
if (time() - filemtime($filename) <= 60*60*24*1)
$iplist = explode(";", file_get_contents($filename)); // Read cached resolved ips
}
// If file was not loaded or found -> generate ip list
if (!$iplist)
{
$iplist = array(); $c=0;
foreach ( $ipchecklist as $k => $iptoresolve )
{
// gethostbyname: It's a VERY SLOW function. We really need to cache the resolved ip list
$ip = gethostbyname($iptoresolve);
if ($ip != "") $iplist[$c] = $ip;
$c++;
}
file_put_contents($filename, implode(";", $iplist));
}
if (in_array($_SERVER['REMOTE_ADDR'], $iplist)) // Check if the client ip is allowed
$isipallowed = true;
if (isset($_SESSION)) $_SESSION['isipallowed'] = $isipallowed;
return $isipallowed;
}
For better reliability you could replace the $_SERVER['REMOTE_ADDR']for the get_ip_address()that @Pekka mentioned in his postas "this bounty question"
为了更好的可靠性,你可以替换$ _ SERVER [“REMOTE_ADDR”]为get_ip_address()是@Pekka在他提到的职位为“这个赏金问题”
回答by Scoobeedo Cool
I found a easy answer.
我找到了一个简单的答案。
Because all local drives have C: or D: or F: ... etc.
因为所有本地驱动器都有 C: 或 D: 或 F: ... 等。
Just detect if the second character is a :
只需检测第二个字符是否为 a :
if ( substr_compare(getcwd(),":",1,1) == 0)
{
echo '<script type="text/javascript">alert(" The working dir is at the local computer ")</script>';
$client_or_server = 'client';
}
else
{
echo '<script type="text/javascript">alert(" The working dir is at the server ")</script>';
$client_or_server = 'server';
}

