Reputation: 12552
Well. I read some topics in SO but I not found a very specific answer.
I need to check with PHP if a PHP code is running in local or remote host. Currently I check with $_SERVER['SERVER_NAME']
but it is inconsistent. In this case, if I run PHP with listed IPs like 127.0.0.1
or localhost
it'll consider local, otherwise remote. If I share my IP with a friend, my code still local, but it consider remote because the shared IP isn't listed.
Well, I think that check IP for localhost is not a good idea (except if you know a good method). I tried methods like gethostbyaddr()
and gethostbyname()
but don't work correctly too.
I don't have a PHP code to show, but my code is basically that:
// true = localhost
return $_SERVER['SERVER_NAME'] === '127.0.0.1';
The fundamental question is: what can determine that PHP is running local? What is "local" for PHP? I think that it can solve the problem.
Obs.: I don't have access to CMD/Shell with PHP.
Upvotes: 4
Views: 6363
Reputation: 8289
You could do what most PHP frameworks do and set a flag during your app's bootstrap phase that defines which environment the code is running in. In it's simplest form:
// the setting when run on a dev machine
define('ENV', 'local');
Then it's a simple case of:
if ( ENV == 'local' )
{
// do stuff
}
Upvotes: 5
Reputation: 2432
This is how I do it, which I find more reliable than trying to detect for 127.0.0.1
:
if( strpos(gethostname(), '.local') !== false ) { }
Basically, the hostname's on my workstations all have .local
appended to it. You can change this to match your workstation's hostname entirely.
Upvotes: 4
Reputation: 2872
As far as I know, only you will be able to know what addresses are local or not. Your network could be set up with IP addresses that don't look local at all. PHP cannot as far as I know determine this by itself.
Upvotes: 1
Reputation: 5622
Check $_SERVER['REMOTE_ADDR']=='127.0.0.1'
. This will only be true if running locally. Be aware that this means local to the server as well. So if you have any scripts running on the server which make requests to your PHP pages, they will satisfy this condition too.
If someone is visiting your site via the web, the IP address you see will never be 127.0.0.1 (or ::1 for IPV6), regardless of the usage of a proxy. (Unless of course you're running the proxy yourself on the same server ;)
Upvotes: 1