tags:

views:

158

answers:

5

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);
    }
A: 

Just change:

$country = $_GET['country'];

To this:

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

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

FWH
that's the worst piece of advice one could give
SilentGhost
In this case it's ok because there's a check just after.
FWH
using @ error supressor is quite a stinky code smell, read about code smells on SO
tharkun
`@` is never okay.
deceze
+3  A: 

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
+11  A: 

you should use the following approach:

if (!isset($_GET['country'])) {
    $incoming = $outgoing = $sms = $free = "---";
} else {
    get_rates($_GET['country']);
}
SilentGhost
Actually, I think you want if(!isset(...)) {
Thomas Owens
sure, that was typo. Thanks Thomas
SilentGhost
And fixed. +1. :)
Thomas Owens
You are missing a closing ']' bracket in the if statement
Shoan
thanks Shoan, I should be getting more sleep %)
SilentGhost
+1  A: 

"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
+1  A: 

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