1

I try to get the country code with php. I use the following code but get this warning:

Undefined index: country_code

function getIP($ip) {
    $curl = curl_init();

    curl_setopt_array($curl, array(
    CURLOPT_URL => "http://ipwho.is/".$ip,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "utf8",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "accept: application/json",
        "content-type: application/json"
    ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    //print_r($response);
    curl_close($curl);

    if ($err) {
    return "cURL Error #:" . $err;
    } else {
    return $response;
    }
}

function isIndo($ip) {
    $ip = getIP($ip);

    $info = json_decode($ip, true);
    //print_r($info);
    if( $info['country_code'] == "ID" ) {
        return true;
    } else {
        return false;
    }
}

Where's the fault?

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • We can't see the data you're getting back from the API, can we? So we cannot tell you what to do instead. Show us the output of print_r($info). – ADyson Aug 03 '22 at 12:40
  • Then again, if you read the answer here: [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) it will teach you how to understand the data structure for yourself and know how to access the items within it correctly. – ADyson Aug 03 '22 at 12:40

3 Answers3

1

Have you tried isset()?

try to check if the array key exists before you access it

if( isset($info['country_code']) && $info['country_code'] == "ID" ) {
    return true;
}

link to isset()

Christoph
  • 36
  • 1
  • 5
1

That server must have returned some error without actually returning an HTTP error, so your code thinks everything is alright and will return a success. You need to verify what you're getting as a response with something like var_dump, var_export or print_r. You can also null coalesce using something like $info['country_code'] ?? '' or isset($info['country_code']).

Rafael Dantas
  • 78
  • 1
  • 7
1

you can isset for check country_code exit or not

if( isset($info['country_code'])) {
  if( $info['country_code'] == "ID" ) {
      return true;
  } else {
      return false;
  }
}else{
  return false;
}
Yasir Mehmood
  • 296
  • 2
  • 11