Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if PHP is running in local server

Tags:

php

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.

like image 259
David Rodrigues Avatar asked Dec 20 '22 13:12

David Rodrigues


1 Answers

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
}
like image 177
Mathew Avatar answered Jan 06 '23 21:01

Mathew