I am trying to sanitize 54 variables at once.
Currently I am doing them one by one like so
if($vissuedate != '') {
$vissuedate = filter_var($vissuedate, FILTER_SANITIZE_STRING);
if($vissuedate == ''){
$vvalidate++;
}
}
I have a whole bunch more and want to ask if there is a way to validate all of them in one go?
You could put all the keys from $_GET in an array:
$get_array = array_keys($_GET);
Or, if you want to skip some, you could use your own array:
$get_array = array('name','adress','phone',...);
Then:
foreach($get_array as $v=>$key){
//check if exists
if(!isset($_GET[$key]){
//do something
}
else{
//do sanitizing here }
}
}
Or even, if you want to do different kinds of sanitizing, you could use an array with number:
$get_array = array('name'=>1,'adress'=>1,'phone'=>2,...);
foreach($get_array as $v=>$key){
//check if exists
if(!isset($_GET[$key]){
//do something
}
else{
switch($v){
case 1:
//do something here;
break;
case 2:
//do something else
break;
}
}
}
}
You can iterate through your $_GET like this:
<?php
foreach($_GET as $key => $value) {
if($_GET[$key] != '') {
$vissuedate = filter_var($_GET[$key], FILTER_SANITIZE_STRING);
if($vissuedate == ''){
$vvalidate++;
}
}
Or as you says assign them all to an array and then attempt to validate from there
Related
HTML markup
<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..
I pass that two array data from jquery to php, i need check if the field is empty by php and exit when find one of them is empty.
But i dont want do it one by one, can it done by php function like foreach or other?
This is what i tried but fail.
$data_one = $_POST['one'];
$data_two = $_POST['two'];
if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Above code keep return field are filled message, whether i fill the input field or not.
Thanks so much.
$allFilled = true;
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
$allFilled = false;
exit('some fields are empty');
}
}
if($allFilled){
exit('all fields are filled');
}
Making use of array_filter and count functions
<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables
$data_two = $_POST['two'];
if (count($data_one_filter) === $data_one_count) {
exit('fields are filled');
} else {
echo('some fields are empty');
// continue other function
}
You are sending data as array. So you seed to check this data as array like this:
$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];
if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Try this
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
exit('some field are empty');
}
}
echo "All fields are filled";
I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.
I've been trying to work my way to it simply must check it with all inputs in the present that I might have 100 lines so got it done less to just check it all together for an error or what?
What I think about that: instead of taking 14 lines of code that make it less but may be the same,
if($_POST["email"] == "")
{
$error = 1;
}
if($_POST["pass1"] == "")
{
$error = 1;
}
if($_POST["pass2"] == "")
{
$error = 1;
}
if($_POST["fornavn"] == "")
{
$error = 1;
}
if($_POST["efternavn"] == "")
{
$error = 1;
}
if($_FILES["file"] == "")
{
$error = 1;
}
Just create an array of field names and loop over them...
foreach(array('email','pass1','pass2',...) as $field) {
if(empty($_POST[$field])) {
$error = 1;
}
}
$_FILES you will have to handle separately. You can create another loop if you want. The structure of $_FILES is different though; I think you should be checking the "error" field. Check the docs.
Another way to approach this, considering the fact that you don't seem to be performing different tests for each field, or responding with specific error messages, is to use array_diff_key:
$names = array('email', 'pass1', 'pass2', 'fornavn', 'efternavn', 'file');
$names = array_keys($names); // convert $names to keys
$posts = array_filter($_POST); // filter out any falsy values
$fails = array_diff_key($names, $posts); // check for the differences
$error = $fail ? 1 : 0;
If you then wish to respond with specific messages depending on what is missing, you already have a list of the problem parameters in $fails. If you wish to extend the above to take into account specific value checks, you could write your own array filter callback function and pass it's name as the second parameter to array_filter... however this wont allow you to choose a different filter response based on array key, only on array value. All because rather annoyingly array_filter doesn't receive a key value when filtering an array.
I'd like some help please, if its possible.
I have created two functions in order to display some messages when is set a $_GET after a redirect.Here's the code:
function display(){
if(isset($_GET['cnf_upd']) && $_GET['cnf_upd'] == '1'){
$value = "The update was successful!";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_upd']) && $_GET['err_upd'] == '1'){
$value = "The Update failed.";
$type = "error";
construct_the_div($value, $type);
}
if(isset($_GET['cnf_del']) && $_GET['cnf_del'] == '1'){
$value = "Deleted completely.";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_del']) && $_GET['err_del'] == '1'){
$value = "Unable to delete.";
$type = "error";
construct_the_div($value, $type);
}
}
function construct_the_div($value, $type){
// creating a div to display the message results
$div = "<div class=\"{$type}Msg\">\n";
$div .= "<p>{$value}</p>\n";
$div .= "</div><!-- end of {$type}Msg -->\n";
echo $div;
}
What I'd like to make is to try to improve the display function, as it gets longer and longer, so that there whould be only one (or two at most) if statement(s) if possible. So the value of the GET will be dynamicly inside the if condition and also if it has the preffix 'cnf_' it wil be a 'confirmMsg' and if it has the preffix 'err_' it wil be a 'errorMsg'.
Is it possible to make something like this???
function display() {
$messages = array(
'cnf_upd' => 'The update was successful!',
'cnf_err' => 'The Update failed.!',
// ...
// add all error and confirm there
// ...
);
foreach($_GET as $key => $value) {
if(strpos($key, 'cnf_')===0) {
$type = 'confirm';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
if(strpos($key, 'err_')===0) {
$type = 'error';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
}
}
The approach is not correct, it seems that only one message should occur at once (there cannot be "deleted completely" and "unable to delete" at once).
Try construct the parameters this way: ?msg=upd&msgType=cnf
function display(){
if (isset($_GET['msg']) && isset($_GET['msgType']))
{
$messages = array('cnf_upd'=>'The update was successful!',
'err_upd'=>'The update failed!',
'cnf_del'=>'The deletion was successful!',
'cnf_upd'=>'The deletion failed!',
);
if (isset($messages[$_GET['msgType'].'_'.$_GET['msg']))
construct_the_div($messages[$_GET['msgType'].'_'.$_GET['msg']], htmlspecialchars($_GET['msgType']));
}
there is still much to improve, but for start this is cleaner and safer.
I'm going to propose a different solution. Instead of setting different parameters in $_GET based on the message to be sent, set one parameter and parse its value.
// Start by setting integer constants:
define(CNF_UPD, 1);
define(ERR_UPD, 2);
define(CNF_DEL, 3);
define(ERR_DEL, 4);
Then when you set the value un $_GET, use the constant:
// Build the URL with a deletion error...
header("Location: http://example.com/script.php?msg=" . ERR_DEL);
Finally, use a switch to parse them
if (isset($_GET['msg'])) {
switch ($_GET['msg']) {
case CNF_UPD:
// Updated...
break;
case ERR_UPD:
// failed...
break;
// etc...
default:
// invalid code.
}
}
If you use a pattern of confirm/error/confirm/error for your integer constants, you can determine which it is by taking $_GET['msg'] % 2. Odd numbers are confirmations, evens are errors. There are of course many other ways you could lay this out, I just happen to have typed them in the alternating order you used. You could also do positive integers for confirmations and negatives for errors, for example.
$type = $_GET['msg'] % 2 == 1 ? $confirm : $error;
This is easily expanded to use multiple messages as well. Since they are integer values, you can safely construct a comma-separated list and explode() them when received.
$messages = implode(array(ERR_DEL,CNF_UPD));
header("Location: http://example.com/script.php?msg=$messages");
Unless you can somehow generate $value and $type based on the $_GET parameter (which I can't see how you would do), you could do something like:
$messages = array();
$messages[] = array('id' => 'cnf_upd', 'value' => 'The update was successful!', 'type' => 'Confirm');
$messages[] = array('id' => 'err_upd', 'value' => 'The Update failed.', 'type' => 'error');
...
foreach ($messages as $message) {
if(isset($_GET[$message['id']]) && $_GET[$message['id']] == '1'){
construct_the_div($message['value'], $message['type']);
}
}
I have these fields: weight, size_1, size_2, size_3
How can I check so minimum one of these fields are filled.
If its under the minimum then it should output "Error, fill one atleast"
I can do this with long if statements, that checks for empty, but is their a better way?
The fields come from an form submission, so it looks like this to get them:
$_POST['weight'];
$_POST['size_1'];
$_POST['size_2'];
$_POST['size_3'];
Assuming they are all in an array:
function check_for_input($array){
foreach($array as $value){
if($value != "") return true;
}
return false;
}
Use it like so:
if(check_for_input($_POST)){ /*...*/ }
else { die("Error, fill one at least"); }
Update with filter:
Assuming they are all in an array:
function check_for_input($array, $filter){
foreach($array as $key=>$value){
if($value != "" && in_array($key, $filter)){
return true;
}
}
return false;
}
Use it like so:
$filter = array('weight', 'size_1', 'size_2', 'size_3', /*...*/);
if(check_for_input($_POST, $filter)){ /*...*/ }
else { die("Error, fill one at least"); }