I am making a survey website. I just want to know if it's really necessary to validate each and every POST data into the database by using isset and !empty. I have around 30 columns and I find it redundant.
Is there any cleaner way than this?
EDIT:
And how about if I have optional fields? How do I come about that?
You can do this such way:
PHP 5.5:
if(!empty(array_filter($_POST)))
{
//there are non-empty fields in $_POST
}
PHP <5.5:
$filtered = array_filter($_POST);
if(!empty($filtered))
{
//there are non-empty fields in $_POST
}
this difference is because before PHP 5.5 empty() was not able to accept non-variables (i.e. expressions, for example)
Edit: if you have some optional fields, then you can deal with this, for example, with having list of mandatory fields:
$array = ['one'=>36, 'two'=>null, 'three'=>'data', 'four'=>0];
$mandatory = ['one', 'three'];
$data = array_intersect_key($array, array_flip($mandatory));
if(!empty($data))
{
//all mandatory fields are not empty
}
Related
Code used for processing form $_POST submissions is working well on most forms but suddenly broke on a new set of forms. I can't see any difference in the forms themselves as it's based purely on the posted values and I have it fixed but I am curious why the sudden problem.
There are some cases where specific post values are not to be processed and those, when they are not needed, are in $RemoveFields as a comma-separated list which is converted to an array and on the one set of forms, it doesn't matter if $RemoveFields has any value or not but on the other set it crashes when empty.
By adding a conditional I was able to make it work but can anyone tell me what the problem is on the original code? Both the old and new are below. The first works on only some of the forms while the second seems to work on all.
The original code:
// Remove unneeded fields specified in $RemoveFields variable
if (isset($RemoveFields) && !is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
$filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
The same code but with a conditional for the $filteredarray value:
// Remove unneeded fields specified in $RemoveFields variable
if (isset($RemoveFields) && !is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
$filteredarray = (isset($RemoveFields)) ? array_diff_key($_POST, array_flip($RemoveFields)) : $_POST;
In the original code, you call array_flip($RemoveFields) even when $RemoveFields is not set. This fails because the argument to array_flip() must be an array.
You should use isset() to protect both lines of code:
if (isset($RemoveFields)) {
if (!is_array($RemoveFields)) {
$RemoveFields = array($RemoveFields);
}
$filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
} else {
$filteredarray = $_POST;
}
I noticed (reading logs of websites I administer), hackers try to submit post requests, literally "inventing" post variables names.
Some website features old PHP code, eg.
if (isset($_POST["mail"]) && !empty($_POST["mail"])) {
//...
}else{
exit;
}
This basically checks if there is a $_POST variable "mail" and it is not empty.
Is it possible to check for the existence of any $_POST variable that it is NOT "mail" and exit the script in that case?
Use array_diff_key to check for differences:
$whitelist = ['mail' => null];
$hasOthers = !empty(array_diff_key($whitelist, $_POST));
I have a different way using filters and not accesing directly to $_POST.
At first, you have to create a definition of what $_POST elements you are interested in. So you have to create an array with the corresponding filters, as example for login definition
$definition = array(
["mail"] => FILTER_SANITIZE_EMAIL,
["passwd"] => FILTER_SANITIZE_STRING
);
Next you can filter all the desirable $_POST elements with filter_input_array
$desirablePost = filter_input_array(INPUT_POST, $definition);
And finalyly you can filter again all the $_POST values usign a filter constant (remembering that all $_POST elements are strings).
$allPost = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
So, to know if someone has injected another $_POST fields, we can compare the count() of both arrays.
if(count($desirablePost) !== count($allPost)){
//error or exit(1) ...
}
I've a form where all fields are required so I thought of doing something like this to retrieve all variables from $_POST:
foreach ($_POST as $key => $value) $$key = $value;
Then I validate the data and use the variables where needed.
Is there a quick way to tell if at least one variable is undefined without having to go isset on each and every one of them?
My first idea was to count how many fields I have and compare with count:
if (count($_POST) == 10)
But this is not dynamic, I have to change that number when I add new fields.
How can I do this more efficiently?
If you want a quick and easy way to do it you can do:
if(in_array("", $_POST)) {
//a field is empty
}
I am trying to get multiple value from user input from text field and want to explode or keep adding into if condition statement
Here is my code
foreach ($list['post'] as $item) {
if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ){
$this->list_post($item);
}
}
Now what exactly I am looking for is in if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ) I want allow user to add multiple category ID and each ID will add AND and further id code AND ($item['single']['catid'] != 4)
I never done this before and don't know either this is proper way to do or any other possible better way.
Thanks a lot
You should have some kind of an array of the category IDs you want to check for, for example:
$categories = array(8, 4);
Then you could use something like the in_array(needle, haystack) built-in function of PHP.
Your if condition would become like that one: if (!in_array($item['single']['catid'], $categories)) {.
You should be using the above, but I am going to give you an idea of how it works, so you can understand the principle for more complex issues:
function exists($target, $array) {
foreach ($array as $element) { // Go through each element in the array
if ($element == $target) { // Check to see if any element there is what you are searching for
return true; // Return true, that it does exist, and stop there.
} else {
// Just ignore it...
}
}
return false; // If you get here, it means nothing returned true, so it does not exist...
}
To be used as if (exists($item['single']['catid'], $categories)) {.
It wouldn't work if it was "inside" the if statement because you have to do some processing before evaluating if it exists or not. So you either could have done that before the if statement, and store the result in a variable, or use a function (which PHP provides).
Hopefully the concept will help you fir more complex problems...
Note: this assumes your input is in the form of an array, which you can build via various ways, if not provided as is directly.
Update:
The input you get via the input field is sent through form, to which you specify either POST or GET as a method. Assuming it is POST that you are using, this is how you'd get the input as a string as it was entered in the text field:
$categories_string = $_POST['the_name_field_in_the_input_tag'];
After that you have to understand it as a list of items, let's say separated by commas: 1,3,5,8. Then this is simply separating by commas. You can use explode($delimiter, $string). Like that:
$categories_array = explode(',', $_POST['categories']);
But you cannot trust the input, so you could get something like 1, 2, 3,5,6. The spaces will mess it up, because you will have spaces all around. To remove them you can use trim for example.
$categories = array(); // Create the array in which the processed input will go
foreach ($categories_array as $c) { // Go through the unprocessed one
$categories[] = trim($c) * 1; // Process it, and fill the result. The times one is just so that you get numbers in the end and not strings...
}
Then you can use it as shown earlier, but keep in mind that this is just an example, and you might not even need all these steps, and there are much more efficient ways to process this input (regular expressions for example). But the concern here is not sanitizing input, but keep in mind you will need to do that eventually.
Hope it's clear enough :)
You might be better off with in_array() for checking a value against a variable number of possibilities.
I'm not sure I understand your problem. You want user to be able to input different values, e.g.:
$string = "5, 6, 7, 8, 10";
Afterwards, you want to check if 'catid' is not in that array and if it isn't you want to run $this->list_post($item);
If so, then you should use something like this:
$values = explode(", ", $string); //make array from values
foreach ($list['post'] as $item) {
if (!in_array($item['single']['catid'], $values)) { //check whether catid is in array
$this->list_post($item); // execute whatever you want
}
}
Hope it helps.
I'm trying to validate some form data before adding it to a database however I need to validate that the option was an option that is in the form, not just one that was added with something like Firebug.
I tried using if and comparing the posted values like this: (there is another 27 options, and 3 more option fields)
if($data['selection'] == 'some_option' || $data['selection'] == 'some_option2') {
However it makes extremely long lines of code and its difficult to manage. So I thought about making an array that stores the possible options, then when its submitted, check if the selected option matches one of the entries in the array.
One of my ideas was to do a loop and check if it's equal:
for($i = 1; $i < sizeof($options[$currentselection]); ++$i) {
if($option[$i] == $data[$currentselection]) {
return true;
} else {
return false;
}
}
However I'd have to do one of these for each of the selection fields (which I'd rather not do). So is there a way of cleaning it up and having it all in one? Also, I'm using codeigniter.
A simple way is to use the in_array function
$values=Array('op1','op2',...);
return in_array($data['selection'],$values);
Or you can do this:
$values=Array(
'selection'=>Array('op1','op2'),
'another_field'=>Array('op3','op4'),
);
return in_array($data[$field],$values[$field]);