4

I have this code and it's giving me an undefined error if country is not a variable in the URL. I've never had this problem before so it's obviously something to do with server settings but I'd rather not change those because this is probably done for security purposes. I've searched Google and can't find the workaround, although I'm sure it's blindingly obvious!

$country = $_GET['country'];

    if(!$country){
        $incoming = $outgoing = $sms = $free = "---";
    } else {
        get_rates($country);
    }
zuk1
  • 18,009
  • 21
  • 59
  • 63

5 Answers5

14

you should use the following approach:

if (!isset($_GET['country'])) {
    $incoming = $outgoing = $sms = $free = "---";
} else {
    get_rates($_GET['country']);
}
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
4

isset allows you to check if the variable exists (if not we give it the value false).

$country = isset($_GET['country'])?  $_GET['country'] : false;
Thirler
  • 20,239
  • 14
  • 63
  • 92
2

"Undefined index" means that element doesn't exist in the array. Your server is probably set to report these errors, while your system so far wasn't. Check if the element exists before accessing it.

$country = null;
if (!empty($_GET['country']) {
    $country = $_GET['country'];
}
deceze
  • 510,633
  • 85
  • 743
  • 889
1

You should probably check to see if $_GET['country'] is set. I would wrap the entire code block you posted in an if statement that checks if the country field is set, using the isset function.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
-1

Just change:

$country = $_GET['country'];

To this:

$country = @$_GET['country'];

'@' is an operator which will remove errors output.

FWH
  • 3,205
  • 1
  • 22
  • 17
  • 10
    that's the worst piece of advice one could give – SilentGhost Jul 16 '09 at 11:40
  • In this case it's ok because there's a check just after. – FWH Jul 16 '09 at 11:41
  • using @ error supressor is quite a stinky code smell, read about code smells on SO – markus Jul 16 '09 at 11:42
  • 3
    @ IS OK for some contexts, in conscious use. It is NOT A DEPRECATED operator. The main typical use is with $_POST and $_GET, like ''. The FWH suggestion is good: initialize $contry with '' or with a value, there are NO SIDE EFFECT! – Peter Krauss Sep 25 '11 at 15:04