Share via:

PHP: Obtain the Visitors IP Address

Tutorial showing how to obtain the IP address of a visitor from PHP.


Edited: 2019-11-03 18:31

PHP tutorial

Identifying the IP address of a visitor from PHP can be a difficult task, since there are ways to change your IP and hide it while browsing the web.

Ignoring that for now, the easiest way to get the IP of a visitor is to use the REMOTE_ADDR variable plainly.

The below code can be used to show the IP address of a visitor:


In your case, this should result in:

Your IP should be shown here if JavaScript is enabled in your browser!

Source: ip.php

Obtaining the visitors IP

The REMOTE_ADDR variable is not very reliable, since it will only give us the IP of the device that sent a request to our server.

Because there are ways "tunnel" requests through other devices, it is difficult to know the real IP of the visitor. However, since most visitors are not using proxies or VPNs, this does actually not matter much.

Even in cases where someone is hiding their IP while doing bad stuff, such as posting spam, you can still block the IPs individually, since the addresses are likely to be proxy servers often abused by spammers.

When to block an IP

I suggest not to block an IP on the first few offences, but only block it on repeated offences.

Due to the dynamic and changing nature of the Internet, you should also have some type of block time out. Depending on how long the abuse has lasted, you could extend the block timer. For someone who has spammed you for years, you could make the block last for years.

When you block an individual IP, it is also a good idea to show a message to the visitor, telling them why their IP address is blocked. You should also consider allowing users to create an account to circumvent a IP-based block, since there might be innocent users using the same IP.

You should not block tor exit nodes, known proxies or VPN IP addresses, without having observed prior abuses happening, as innocent users might be hit in collateral damage.

Most blocking can be handled automatically. For example, Apache has the mod_security module which will help secure your website against spammers and brute force attacks.