Last updated on November 11th, 2022 at 11:59 am

In this tutorial we are going to see how quickly we can get the ip address of the system [usually assigned by ISP], the public ip address using PHP.

For any Server (Linux or Windows)

In order to make things simpler let us use a public website that shows just your IP address if you hit that in the browser. We are using https://checkip.amazonaws.com

Now to use the above URL within a PHP code we need to utilize cURL. Typically new versions of PHP comes with cURL support, but incase if you don’t have curl module please configure that to your PHP configuration before running the below script

<?php
$ch = curl_init();
$curlConfig = array(
    CURLOPT_URL            => "https://checkip.amazonaws.com",
    CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);

// result sent by the remote server is in $result
echo $result;
?>

Output of the above script. I saved the file as curl.php

root@production-server:~# php curl.php
128.135.61.13
root@production-server:~#

This code will only run on Windows server.

ob_start();
system('ipconfig /all');
$mycom=ob_get_contents(); // Capture the output into a variable
ob_clean();
$findme = "IP Address";
$pos = strpos($mycom, $findme);
$ip=substr($mycom,($pos+36),17);
echo "The IP address of this system is :".$ip;

Check Get MAC Address Using PHP (Linux & Windows)
Here we are using Output buffer. CLICK HERE to take a look at what is Output buffering in php.

Leave a Reply

Your email address will not be published. Required fields are marked *