Is it safe to trust $_SERVER['REMOTE_ADDR']?

Silver Light picture Silver Light · Jan 23, 2011 · Viewed 53.4k times · Source

Is it safe to trust $_SERVER['REMOTE_ADDR']? Can it be substituted by changing the header of request or something like that?

Is it safe to write something like that?

if ($_SERVER['REMOTE_ADDR'] == '222.222.222.222') { // my ip address
    $grant_all_admin_rights = true;
}

Answer

sagi picture sagi · Jan 23, 2011

Yes, it's safe. It is the source IP of the TCP connection and can't be substituted by changing an HTTP header.

One case you may want to be worry of is if you are behind a reverse proxy in which case the REMOTE_ADDR will always be the IP of the proxy server and the user IP will be provided in an HTTP header (such as X-Forwarded-For). But for the normal use case reading REMOTE_ADDR is fine.