Server public IP address in PHP with redundancy

last updated August 19, 2021 16:23 UTC

It is sometimes necessary that your code knows your server or component’s external/public IP address. Often there are load balancers, firewalls, container networks, caches etc., in place, and therefore the most reliable way is to use one of the online IP lookup services.

I have created a script in PHP that uses multiple such services. It covers several requirements:

  • deliver the IP address at speed; there is a file saved during the first lookup, and the subsequent calls use it until overridden
  • uses only free services that do not require registration
  • redundancy; atm there are 10+ service fallbacks in the script
  • diagnostics; it is possible to call all the lookups in the “run all” mode

Example of the usage:

$myIP = this_servers_public_ip ($purge, $runall);
 
# $purge = true .. reinstates the local file
# $runall = true .. runs through all the services

Using this function, you get a fast and reliable way of knowing the IP address whenever you need it. You can download the script here (gzip).

Shopping Cart
There are no products in the cart!
Total
 0.00
0