EllisLab/CodeIgniter — pull request #1700 by WDC (2012-08-13 03:15:35+00:00)
Title: Adds get_numeric_input()

This is a copy from my StackOverflow Q&A post: http://stackoverflow.com/questions/11927690/how-can-i-quickly-check-if-get-and-post-variables-in-codeigniter-are-both-set-an

## get_numeric_input() for CodeIgniter ##

> mixed **get_numeric_input** ( string *$name* [, bool *$required* = *True* [, string *$source* = *"GET"* [, bool *$xss_clean* = *True* ]]] )

Below is a function that I created because I was tired of checking if GET and POST variables existed and were numeric.

This was mainly used when handling errors or status messages, because I could use `redirect("original_page.php?error=1");` to pass an error to the original page. On the original page, I could simply do `if (isset($error)) { … }` and display a message depending on the value. However, it was necessary to check these variables before sending them to the view in the interest of security. This process proved to be quite repetitive and tedious.

This function below is to be added to the bottom of `wwwroot/application/system/core/Input.php`

It is to be used as follows:

**Example 1:**

function index() {
if ($error = $this->input->get_numeric_input('error', True, "GET", True)) {
$data['error'] = $error;
}
}

In this example, if `$_GET['error']` is both set and numeric, it will set `$data['error']` to that value. If it is either not set and/or not numeric, it will **terminate** the script.

**Example 2:**

function index() {
if ($error = $this->input->get_numeric_input('error', False, "POST", True)) {
$data['error'] = $error;
}
}

In this example, if `$_POST['error']` is both set and numeric, it will set `$data['error']` to that value. If it is either not set and/or not numeric, it will *continue* and not set any values in the $data array.

The first argument is the variable name to be checked. The second variable is the boolean that makes the check required or not. If you have this set to TRUE, then if the variable is not set OR if it is not numeric, it will show an error and immediately terminate the script. If set to False, then it will will simply return False, and the script will move on. The third variable is either POST or GET, and will determine if the function looks for the variable in the $_GET or $_POST arrays. Finally, the fourth variable indicated whether or not the values will be XSS_CLEAN when returned.

**NOTE:** Both the second, third, and fourth arguments are optional, and default to True, “GET,” and True, respectively.