← Back to blog home

quick php get post request isset function

05 Dec

When checking the values of $_GET / $_POST / $_REQUEST it is often necessary to check them with isset to ensure that they are defined to avoid undefined index warnings. Here are 3 VERY simple functions that every programmer can use to avoid ever running in to these problems.

The functions are all the same and I use short names GV, PV, RV (Get Value, Post Value, Request Value). In addition to handling the isset for you the code also allows you to specify a default value. The best part of all the functions are only 1 simple line of code each.

 

//GET
function GV($key,$default=""){
   return (isset($_GET[$key])) ? $_GET[$key] : $default;
}

//POST
function PV($key,$default=""){
   return (isset($_POST[$key])) ? $_POST[$key] : $default;
}

//REQUEST
function RV($key,$default=""){
   return (isset($_REQUEST[$key])) ? $_REQUEST[$key] : $default;
}

 

Using these functions is about as easy as it gets… Usage:

//just like $_GET['MyKey'] but it handles the isset for you
$myVar=GV('MyKey');
//using default with a post value (default is optional)
$myVar2=PV('MyKey','yes');

 

So in the first example the function will return the value of MyKey or an empty string if the get value MyKey is not set. In the second example it will check the post value for MyKey and if it's not set it will return the string "yes" as defined in the default value.

 

Hope these quick little functions can be helpful to some people.

 
 

Leave a Reply

Notify me of future comments

(I don't spam or share your e-mail. Unsubscribing is as easy as clicking the "unsubscribe" link in the notifications)