How can I quickly validate if a GET or POST variable in CodeIgniter is both set and numeric for use as error or status messages in views?
It is very tedious to do something like this each time each time I want to check variables:
if ($this->input->get('error', True)) {
if (is_numeric($this->input->get('error', True))) {
$data['error'] = $this->input->get('error', True);
}
}
get_numeric_input() for CodeIgniter
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 doif (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.phpIt is to be used as follows:
Example 1:
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:
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.
Here is the code: