当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to determine with JavaScript, if the user is in internal or external Network?

问题描述:

I have a button with a JavaScript that 'calls' a php-file.

The site is accessible from the internal network and from the world wide web.

If I click the button from www the php is not working because the address in the JavaScript is an internal 192.168.x.x adress.

function doSomething(id)

{

var url ="http://192.168.1.1/phpfile.php?id" +id;

var win = window.open(url, '_blank');

if(win){

//Browser has allowed it to be opened

win.focus();

}

else

{

//Broswer has blocked it

alert('Please allow popups for this site');

}

}

Is it possible to differentiate if the call is from the internal or another network?

In another case (php) I use an if-else to solve the problem

((substr($_SERVER['REMOTE_ADDR'],0,8) == "192.168.") ||($_SERVER['REMOTE_ADDR'] == "127.0.0.1"))

? 'http://internal/address/' : 'http://my.external.de/''

网友答案:

As far I understand, you want your web site to work locally with localhost/192.168.x.x/127.0.0.1 or on the remote web server and distinguish which configuration you have so your javascript switch properly from one to the other.

First, you cannot get your IP address from javascript directly, you need to use a relay web site for this: see this thread for the answer.

But, in your case I believe there is a much more simpler way to proceed, and without any 'if'. Javascript (or the browser) is smart enough to route calls for you. Change your code to this:

function doSomething(id)
{
        var url ="/phpfile.php?id" +id;

        var win = window.open(url, '_blank');
            if(win){
                //Browser has allowed it to be opened
                win.focus();
            }
            else
            {
                //Broswer has blocked it
                alert('Please allow popups for this site');
            }
}

Your client browser will route the call to localhost automatically, if you loaded the page running the script, from localhost. And route to my.external.de, if you loaded the page running the script, from my.external.de.

网友答案:

If the button and the JavaScript-code reside in a HTML page delivered from the same server, it can test and set the correct value, before delivering this page.

$PREFIX = ((substr($_SERVER['REMOTE_ADDR'],0,8) == "192.168.") ||($_SERVER['REMOTE_ADDR'] == "127.0.0.1")) ? 'http://internal/address/' : 'http://my.external.de/''

function doSomething(id) { var url ="<?=PREFIX?>phpfile.php?id" +id; ....

分享给朋友:
您可能感兴趣的文章:
随机阅读: