Properly testing for request variables

When you’re starting out in PHP you might find sometimes variables don’t exist when you want them to and you’ll get the NOTICE message from the PHP interpreter.  With the methods below the variables will always be defined so you can test if they’re what they’re supposed to be and rely that they’re there.  For security’s sake you’ll want to verify all user data passed into your application as well and type check when you can.

If the URL var get is passed in and it’s an integer, assign it to $id, otherwise it will be 0.

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

 

If $flag is passed in as a post, true, else false.

$flag = isset($_POST['flag']) ? true : false;

 

Looking for if request variable ’email’ exists in the GET or POST scope.

$params = array_merge($_GET, $_POST);

$email = isset($params['email']) ? $params['email'] : '';

Leave a Reply

Your email address will not be published. Required fields are marked *