I recently installed the WAMP server package on my computer at work. When I first started messing around with PHP(not too long ago), I installed PHP, MySQL, and Apache manually. Well, the application I have been working on is now giving me a WHOLE BUNCH of Notice messages:
Notice: Undefined index: lookatLon in C:\wamp\www\coordinates.php on line 3
Well, as it turns out, I have learned that I am handling my assigning of $variable = $_REQUEST['whatever']; all wrong. For example... I have a script that accepts a $longitude and $latitude from a $_GET['longitude']; and $_GET['latitude'] .... but under certain circumstances, the page is loaded without any 'longitude=' or 'latitude=' in the url.
Now I am getting these notices that it isn't liking my unset variables.
So, my question is, what is the proper way to handle a situation, where sometimes there is GET or POST information available and sometimes there isn't. I just read that it is not a good idea to shut off the notices(which would surely fix my problem), but rather the solution is to code properly.
So what is the proper way to account for GET or POST data that may or may not be there, depending on the situation?
To get values you have to initialize variables, like this
$longitude = '';
$latitude = '';
if (isset($_GET['longitude'])) $longitude = $_GET['longitude'];
if (isset($_GET['latitude'])) $latitude = $_GET['latitude'];
and later use assigned variables
To control the program flow you may query the request variable directly:
if (isset($_GET['id'])) {
//get data
}
See if the value is set. (http://php.net/manual/en/function.isset.php)
$myvar = "";
if(isset($_GET["myvar"])) $myvar = $_GET["myvar"];
Don't forget to check at appropriate places in your code that you have a valid value, cleanse user input,etc...
You have to wrap the variables with an isset()
test:
if (isset($_REQUEST['whatever'])) {
if ($_REQUEST['whatever'] == '.....') {
}
}
You COULD, in the short term, use the @
error-supression opreator, but that's a short-term fix and only fogs up the problem. You COULD also disable the warnings at the php.ini level, but again, that's just a short-term unreliable fix. The best solution is to use the isset() wrappers everywhere. Painful, but the best long-term solution.
The easiest way I've found to handle it is to use the isset() function like so:
if(isset($_GET['foo']))
{
//do whatever with $_GET['foo']
}
The non-mandatory and somewhat less readable ternary solution:
$myvar = ( isset($_GET['myvar']) ? sanitize($_GET['myvar']) : 'default value' );
sanitize()
is simply a generic placeholder function for sanitizing input.