A better way to handle POST and GET in PHP

Posted on

To handle POSTed and GET variables in PHP is a bit of a pain. You’ve got to check that they are actually set, that they are not null and then, read the value. We use three functions to handle this. Why three? Well, one of them (validateParam) can be used in multiple situations. Here’s the code:

function validateParam($param, $default = "") {
if (!isset($param) || $param=="") {
 return $default;
}
return $param;
}

function doGet($param, $default = "") {
if (array_key_exists($param, $_GET)) {
 return validateParam($_GET[$param], $default);
}
return $default;
}
function doPost($param, $default = "") {
if (array_key_exists($param, $_POST)) {
 return validateParam($_POST[$param], $default);
}
return $default;
}

Now all you need to do is call doPost(“var_name”, “default”) or doGet(“var_name”, “default”) and don’t have to bother about isset(), etc. Hope this helps when processing these.

This entry was posted in Web Development. Bookmark the permalink.

Leave a Reply

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