How to check if the php script is running on a local server?

前端 未结 6 2068
伪装坚强ぢ
伪装坚强ぢ 2021-02-15 00:44

Is it possible to check if the website (php) is running locally or on a hosted server? I want to enable some logs if the website is running locally and I don\'t want these to ap

相关标签:
6条回答
  • 2021-02-15 01:08

    I have build this function that checks if current server name has name server records, normally local server don't has.

    <?php
    function isLocal ()
    {
      return !checkdnsrr($_SERVER['SERVER_NAME'], 'NS');
    }
    ?>
    
    0 讨论(0)
  • 2021-02-15 01:14
    $whitelist = array(
        '127.0.0.1',
        '::1'
    );
    
    if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
        // not valid
    }
    
    0 讨论(0)
  • 2021-02-15 01:20

    You should automate deployment

    This is not directly the answer to your question, but in my opinion the better way. In an automated deployment process, setting a variable like $local = true, like other configuration values (for example your db-connection), would be no manual, error prone, task.

    Checking for 'localness' is in my opinion the wrong way: you dont want to show your logs to every local visitor (a Proxy may be one), but only when deployed in a testing environment.

    A popular tool for automated deployment is Capistrano, there should be PHP-Centric tools too.

    0 讨论(0)
  • 2021-02-15 01:22

    Just in case this is useful to anybody, I made this function as the above answers didn't really do what I was looking for:

    function is_local() {
        if($_SERVER['HTTP_HOST'] == 'localhost'
            || substr($_SERVER['HTTP_HOST'],0,3) == '10.'
            || substr($_SERVER['HTTP_HOST'],0,7) == '192.168') return true;
        return false;
    }
    
    0 讨论(0)
  • 2021-02-15 01:23

    I believe the best approach is to 'fake' a testing mode, which can be done by creating a file in your local environment.
    When I used this approach I created an empty text file called testing.txt and then used the following code:

    if (file_exists('testing.txt')) {
        // then we are local or on a test environment
    } else {
        // we are in production!
    }
    

    This approach is 100% compatible with any Operating System and you can use several test files in case you want a more granular approach (e.g. development.txt, testing.txt, staging.txt, or production.txt) in order to customise your deployment process.

    0 讨论(0)
  • 2021-02-15 01:29

    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.

    0 讨论(0)
提交回复
热议问题