0

In theory I know what is causing the errors my question is more if what I'm doing is acctually that wrong or if google app engine is just printing errors that are not that important.

So the code that causes the error:

$test = isValid($_GET["id"])

function isValid($var) {
    return isset($var) AND $var != "";
}

Error:

Notice: Undefined index: id in /base/data/home/apps/somestuff/1.892737377923487/result.php on line 3

So the error says that the index id is undefined, which in some cases it is but I want to check if it is set and if it is not empty, because the form that sends this data sends empty strings in some of the fields so the isset() returns true but it is not valid data.

usbpc102
  • 1,137
  • 13
  • 25

1 Answers1

0

It might be worth checking out variable scoping in PHP to get a handle on why this error is coming up. There are three variables operating in the piece of code above.

In the first line, you set $test to be the returned value of the isValid() function, to which you provide the value of $_GET["id"] as an argument. When there is no $_GET[] variable provided with the name id, however, PHP throws a Notice saying exactly that - that the index is is undefined - but since this is just a notice, and your error reporting is set to tolerate notices, the script just carrys on, and assumes the value of $_GET["id"] to be empty (i.e., "" == false == 0 == null etc.).

In the isValid() function, you have a new variable defined ($var) which is local in its scope, existing only inside the function. Thus, $var will always be defined inside this function, and thus isset($var), inside the function, will always be true. Even when $_GET["id"] is empty, $var will still be defined with the empty value PHP automatically gave to it.

If you wanted to determine whether $_GET["id"] exists, you would have to use the isset() function on this variable, not a locally scoped variable which has been assigned with its value (or lack thereof). Thus, you could get rid of the notice, and have the same effect as before, by using this line of code:

$test = (isset($_GET["id"]) && !empty($_GET["id"]));

Hope this helps, I think the link below might help you out!

http://php.net/manual/en/language.variables.scope.php

Dom Weldon
  • 1,728
  • 1
  • 12
  • 24
  • Thanks! I just notice how stupid my function is. Also is `&&` in some way better than `AND`? – usbpc102 Dec 07 '15 at 18:19
  • Yep, `&&` and `||` have higher precedence than `and` and `or` http://stackoverflow.com/questions/2803321/and-vs-as-operator – Dom Weldon Dec 07 '15 at 18:25