Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 806
BabyCakes Avatar asked Jul 30 '09 23:07

BabyCakes


2 Answers

How about wrapping it in a function?

<?php

function getPost($name, $default = null) {
    return isset($_POST[$name]) ? $_POST[$name] : $default;
}
like image 181
Glass Robot Avatar answered Sep 22 '22 14:09

Glass Robot


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.

like image 40
benlumley Avatar answered Sep 23 '22 14:09

benlumley