No more undefined index using PHP's $_GET and $_POST

7th August 2014 by Ian Martin

No+more+undefined+index+using+PHP%27s+%24_GET+and+%24_POST Image

No more undefined index using PHP's $_GET and $_POST

7th August 2014 by Ian Martin

A function to avoid PHP undefined index warnings

It's very annoying having to check whether $_GET['somevalue'] is set before checking its value - but if you don't, your code is going to throw a a lot of Notice: Undefined index warnings and that's never good. I've written a quick class to make every PHP developer's life a bit easier. It's based on CodeIgniter's $this->input class. You can use it as follows and never have to worry about whether the index exists or not... It will just get set to NULL if it doesn't.


class Input {

     function get($name) {

          return isset($_GET[$name]) ? $_GET[$name] : null;

     }



     function post($name) {

          return isset($_POST[$name]) ? $_POST[$name] : null;

     }



     function get_post($name) {

          return $this->get($name) ? $this->get($name) : $this->post($name);

     }

}

$input = new Input;



$page = $input->get('page'); // // look in $_GET

$page = $input->post('page'); // // look in $_POST

$page = $input->get_post('page'); // look in both $_GET and $_POST