PHP: Obtain the Visitors IP Address

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

950 views
d

By. Jacob

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:

echo $_SERVER['REMOTE_ADDR'] . PHP_EOL;

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.

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials