How to get user info by IP address

I have seen that most people search about how to get user (visitor) info by IP address but they get nothing. So, I thought I write an article regarding this. I found a better way by using API. This API provides us the access to getting user info by IP address. I have created a function to get user info. I have used CURL library to make this work.

We can use file_get_contents() function but we have to enable allow_url_fopen = 0 in the php.ini file, due to some recent website hacks we had to secure sites more. Where we discovered that file_get_contents failed to work whereas CURL work better.

Using CURL we need not enable allow_url_fopen. Here is the following function you can test.

function get_user_info() {       
        $ip = $_SERVER['REMOTE_ADDR'];
        $url = "{$ip}";
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
        $info = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        } else {

        return $location = json_decode($info);
$info = get_user_info(); // returns an array object
var_dump( $info );

object(stdClass)#50 (7) { ["ip"]=> string(15) "" ["city"]=> string(6) "Delhi" ["region"]=> string(13) "Delhi" ["country"]=> string(2) "IN" ["loc"]=> string(15) "28.7823,47.1000" ["postal"]=> string(6) "110002" ["org"]=> string(27) "Xyz Ltd." }

There may be found other methods also but I think it is also good.


Be the first to comment