Get & Store Your Server’s IP Address With PHP

It can be useful to for a server to know its external IP, particularly if you’re hosting a website using a server whose default gateway has an IP that regularly changes.

If you’re hosting any web service (example: a website) as a residential ISP customer, you likely fall into this category. Similarly, if you use a service like Amazon Web Services and choose not to allocate a static IP address to your EC2 instances, your server will often have a new external IP after a reboot.

All of the above comes down to the difference between static and dynamic IPs. It’s absolutely recommended to use a static IP address to host any public-facing web service. An IP is the fundamental compment of an address system in any routable network. Without an IP, a user’s computer wouldn’t  know how to get your server. Having a static IP means that address never changes, which eases the burden on systems trying to locate your server.

It’s difficult to mail holiday greetings to a family member who moves frequently, or to pay a service provider who keeps changing their billing address. Similarly, it’s hard to communicate with a server whose IP changes regularly.

Sometimes you don’t have access to a static IP, though, and what then? Dynamic DNS can be one way to solve this problem, and I plan on addressing (har!) that issue in a future post. Here, I’ll povide PHP code that collects and stores the current server’s IP.

This script uses, a service that will print a client IP in plaintext. This is much like, but without beautiful CSS styles and complex HTML. This makes the page particularly easy to scrape and parse.

The script grabs the contents of the site and checks the result against a regular expression to confirm the site is still reporting an IP, and not a bogus string.

The script uses a basic text file to store the “current” IP, and on each run it checks current.txt to see what the IP was on last run, and compares that to the IP just scraped.

Finally, the last three lines of the code update current.txt if the IP has changed.

You can change the location of current.txt by just changing the path at the top of the script. The variable $current_txt defines this. If you store this file in a location accessible to you remotely (say, a folder synced to Google Drivr or Dropbox) you will always know your server’s IP.

Print "hello"