Home > Back-end >  undefined variable PHP Array
undefined variable PHP Array

Time:08-04

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?

CodePudding user response:

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()

CodePudding user response:

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']).

CodePudding user response:

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;
}
  •  Tags:  
  • php
  • Related