Re: error with null $HTTP_GET_VARS['field']

From: Date: Tue, 17 Jun 2003 20:47:07 +0000
Subject: Re: error with null $HTTP_GET_VARS['field']
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-151895@lists.php.net to get a copy of this message
On Tue, 2003-06-17 at 11:55, Logan McKinley wrote: > right now if a the 'field' key does not exist at all in the querystring it > returns the following error: > Notice: Undefined index: Register in c:\inetpub\wwwroot\PHP\Register.php on > line 3 > I think i can use the empty function but i pass in 11 different variables > and it seems like there must be a more eligant way to prevent the error then > with 11 individual if statements. Is there a way in which it will return a > value even if the key does not exist in the querystring. > Thanks in advance, > ~Logan What you are seeing is the correct behaviour: since the variable has not been initialized, attempting to access it without checking it is not good. Usually it's not much of an issue in PHP, though. Anyway, one of the better ways to deal with it is to loop over your input arrays and checking the values, something like this: <?php error_reporting(E_ALL); ini_set('display_errors', true); $_acceptable_input = array('username', 'password', 'action'); $CHECKED_INPUT = array(); foreach ($_acceptable_input as $input_name) { // Use isset() instead of empty() so you get the blank inputs too. // Also, this would be an excellent place to do any input validation // as a first line of defence against poisoning attacks. if (isset($_GET[$input_name])) { $CHECKED_INPUT[$input_name] = $_GET[$input_name]; } else { $CHECKED_INPUT[$input_name] = false; } } // Now you can use the expected ones without any errors since you know // it's been tested for: switch ($CHECKED_INPUT['action']) { case 'Log in': echo "Logging in with {$CHECKED_INPUT['username']}/{$CHECKED_INPUT['password']}.\n"; break; default: echo "Unknown action.\n"; break; } ?> You could also just turn down error_reporting to skip the NOTICE-level errors, but that's only really recommendable on a production box (where you should probably have display_errors off too)...but on a development server, hiding the problem is not likely to help in the long run. :) Hope this helps, Torben -- Torben Wilson <torben@php.net> +1.604.709.0506 http://www.thebuttlesschaps.com http://www.inflatableeye.com http://www.hybrid17.com http://www.themainonmain.com -----==== Boycott Starbucks! http://www.haidabuckscafe.com ====-----

« previous php.general (#151895) next »