Search code examples
phplocalhostdetection

How can I detect if the user is on localhost in PHP?


In other words, how can I tell if the person using my web application is on the server it resides on? If I remember correctly, PHPMyAdmin does something like this for security reasons.


Solution

  • You can use $_SERVER['REMOTE_ADDR'], which contains the IP address of the client requesting it, as given by the web server.

    $whitelist = array(
        '127.0.0.1',
        '::1'
    );
    
    if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
        // not valid
    }
    

    Note: the original version of this answer suggested verifying the destination hostname using $_SERVER['HTTP_HOST'], which is unsafe because it could in some cases be spoofed by the requester.