Using PHP/cURL to grok your public IP address
I had the occasion to create a PHP page that displays the server’s current public IP address. Not necessarily a good thing to display. But, I have several internal web sites on a development server where the host names are not available on a public DNS server. Displaying the server’s current public IP address is handy to prevent needing to nslookup my dyndns host name when altering my host file.
So, here is how I did it:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "www.checkip.org");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$pattern = '/Your IP: ([\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3})<\/span>/';
$matches = array();
preg_match($pattern, $output, $matches);
$yourIP = 'N/A';
if (count($matches) > 1) {
$yourIP = $matches[1];
}
curl_close($ch);
What I’m doing here is using cURL to get the page at checkip.org and then using a regular expressing to get the IP address returned in that page.
Albeit not completely fault-tolerant, as the web site can change it’s structure, but this type of quick’n'dirty screen scraping was what I needed at the time.






LinkedIn Profile