Tutorial :Is there a better way to check POSTed variables in PHP?



Question:

I find in my PHP pages I end up with lines and lines of code that look like this:

$my_id = isset($_REQUEST['my_id']) ? $_REQUEST['my_id'] : '';  $another_var = isset($_REQUEST['another_var']) ? $_REQUEST['another_var'] : 42;  ...  

Is there a better, more concise, or more readable way to check this array and assign them to a local variable if they exist or apply a default if they don't?

EDIT: I don't want to use register_globals() - I'd still have the isset problem anyway.


Solution:1

How about wrapping it in a function?

<?php    function getPost($name, $default = null) {      return isset($_POST[$name]) ? $_POST[$name] : $default;  }  


Solution:2

a better method might be to create a singleton/static class to abstract away the details of checking the request data.

Something like:

class Request {      private $defaults = array();    private static $_instance = false;      function getInstance () {      if (!self::$_instance) {       $c = __CLASS__;        self::$_instance = new $c;      }      return self::$_instance;    }      function setDefaults($defaults) {      $this->defaults = $defaults;    }      public function __get($field) {      if (isset($_REQUEST[$field]) && !empty($_REQUEST[$field])) {          return $_REQUEST['field'];                } elseif (isset($this->defaults[$field])) {          return $this->defaults[$field];        } else {          return ''; # define a default value here.        }     }  }  

you can then do:

# get an instance of the request  $request = Request::getInstance();    # pass in defaults.  $request->setDefaults(array('name'=>'Please Specify'));    # access properties  echo $request->name;  echo $request->email;  

I think this makes your individual scripts loads cleaner and abstracts away the validation etc. Plus loads of scope with this design to extend it/add alternate behaviours, add more complicated default handling etc etc.


Solution:3

First, use $_POST for POSTed variables. $_REQUEST is a mashup of many different incoming variables, not just $_POST and could cause problems.

One solution for your question would be to create a function that handles the isset() logic.

function ForceIncomingValue($Key, $Default) {      if (!isset($_POST[$Key]))           return $Default;      else return $_POST[$Key];  }  


Solution:4

first of all, NEVER use the $_REQUEST variable, it'll lead to bugs and other problems during development

  function getPOST($key) {      if(isset($_POST[$key])) {          return $_POST[$key];      }  }

note that this code leaves the variable empty when $_POST[$key] was not set

you could also adapt that code to enable you to instead provide you with a (sensible) default when the value could not be loaded.

  function getPOST($key, $default = NULL) {      if(isset($_POST[$key])) {          return $_POST[$key];      } else {          return $default;      }  }


Solution:5

Is the set of variables you're expecting known at the time of the script's writing, or do you want to do this for an arbitrary set of values? If the former is true, you could do something like this:

# This array would hold the names of all the variables you're expecting  # and a default value for that variable name  $variableNames = array (...);   foreach ($variableNames as $key => $default) {      if (isset ($_REQUEST[$key])) $$key = $_REQUEST[$key];      else $$key = $default;  }  

Basically, this takes advantage of PHP's ability to evaluate variables to create other variables (hence the double-dollar for $$key--this means create a new variable whose name is the value of $key).

I haven't yet come up with a good solution to the latter situation.


Solution:6

PHP's null coalescing operator!

$username = $_GET['user'] ?? 'nobody';

For a lot of variables, with a requirement check, anyone is free to use my expect function.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »