如何检查客户端是否是本地的

如何检查客户端是否是本地的

本文介绍了PHP:如何检查客户端是否是本地的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查文件是否本地打开(同一台机器或网络)。我正在使用:

I need to check if a file is opened "locally" (same machine or network). I'm using:

<?php
if ((substr($_SERVER['REMOTE_ADDR'],0,8) == "192.168.") || ($_SERVER['REMOTE_ADDR'] == "127.0.0.1")) {
    // client is local
} else {
    // client is not local
}

但我不确定这是不是最好的办法。

But I'm not sure this is the best way.

这样做有什么更加万无一失的方法?

What is a more foolproof way of doing this?

推荐答案

万无一失,一如既往,可能会非常棘手。

"Foolproof," as always, can be tricky.

如果我们将自己局限于IPv4,那么检查127.0.0.1会处理localhost情况,但是检查192.168。是完全错误的 - 只有在使用16位子网掩码的192.168网络上的服务器上运行脚本时,它才有效。

If we do restrict ourselves to IPv4, then checking for "127.0.0.1" takes care of the localhost case, but checking against "192.168." is plain wrong - it will only work if the script is being run on a server which happens to be on the 192.168 network, using a 16-bit subnet mask.

检查对$ _SERVER ['SERVER_ADDR']的$ _SERVER ['REMOTE_ADDR']将是一个更好的选择。但是,这仍然没有考虑多宿主主机(即除了127.0.0.1之外还有几个IP地址的主机)的情况。

Checking $_SERVER['REMOTE_ADDR'] against $_SERVER['SERVER_ADDR'] would be a better bet. This still doesn't take care of the case of a multi-homed host (ie one which has several IP addresses in addition to 127.0.0.1), though.

In为了捕获所有相同的网络情况,您需要检查SERVER_ADDR和子网掩码的组合对REMOTE_ADDR,但子网掩码在$ _SERVER中不可用。

In order to catch all same-network cases, you'd need to check the combination of SERVER_ADDR and subnet mask against REMOTE_ADDR, but the subnet mask isn't available in $_SERVER.

但我发现了一个功能,可以完成您想要的功能。这是几个屏幕,它叫做clientInSameSubnet。不是我的代码,但看起来是正确的。

BUT I found a function which does pretty much what you want here. It's a couple of screens down and it's called clientInSameSubnet. Not my code, but looks right.

这篇关于PHP:如何检查客户端是否是本地的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:28