Undefined variable: missing in - php

I'm currently trying to figure out PHP. however I keep running into some errors.
this is my PHP line of code that has two errors:
1)Undefined variable: missing
2)in_array() expects parameter 2 to be array
my best guess would be the missing variable ($missing) would be missing however I defined it just above it.
the errors are in the line: if (!in_array($email, $missing))
foreach ($_POST as $key => $value) {
if (in_array($key, $expected)) {
if (!is_array($value)) {
$value = trim($value);
}
if (empty($value) && in_array($key,$required)) {
$$key = '';
$missing[] = $key;
} else {
$$key = $value;
}
}
}
if (!in_array($email, $missing)) {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email){
$errors['email'] = 'use a valid mail address';
}
}

1)Undefined variable: missing
Yes, you've defined it, but only in one branch of the code. You don't guarantee its existence. There's obviously a situation when your variable isn't defined at all and you need to take care of it before trying to use it somewhere.
2)in_array() expects parameter 2 to be array
As the error says, you need to make 100% sure that your second parameter is indeed an array AND is defined.

Related

How do I suppress this foreach warning when the function that contains it relies on $_POST data

I have the following code which functions as intended when $_POST values are set, however, if no $_POST values(IE when the page is first loaded) are set I get "Warning: Invalid argument supplied for foreach() in..." $_POST is always going to be empty until the user clicks submit. I have tried empty(), isset() and now count().
if(isset($_POST['submitbtn'])){
$errors = CheckFormErrors();
if(count($errors) == 0){
$data = CleanFormData();
print_r($data);
}
}
Here is the function being called(not yet complete, but it is working):
function CleanFormData(){
foreach($_POST as $key => $value){
if($key == 'description'){ continue; }
if($key == 'file'){ continue; }
if($key == 'role'){ continue; }
$_POST[$key] = is_array($key) ? $_POST[$key]: strip_tags($_POST[$key]);
}
return $_POST;
}
I thought that I could surpress the error by putting it in a conditional statement, evidently that is incorrect. A little help?
As already stated in comments, you have to check if the superglobal $_POST is empty before calling the foreach itself (inside the function), not outside the function - this way you don't have to check for !empty($_POST) every time you are calling this function.
function CleanFormData() {
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
// Loops here
}
}
return $_POST;
}

PHP Notice: Array to string conversion Error

Been experiencing this error for a little while and can't find any conclusive answers on fixing it. I have tried removing quotes from $key in line 59 but to no avail.
if (!get_magic_quotes_gpc()) {
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
$_POST['$key'] = trim(addslashes($value));
}
}
if (isset($_GET)) {
foreach ($_GET as $key => $value) {
$_GET[$key] = trim(addslashes($value));
}
}
}
LINE 59
$_POST['$key'] = trim(addslashes($value));
Error On Screen
Notice: Array to string conversion in
C:\Inetpub\vhosts\domain.com\httpdocs\library\config.php on
line 59
Check if it is array before you assign it
$_POST[$key] = !is_array($value) ? trim(addslashes($value)) : '';
// ^ Remove the quotes here // ^ Do something
// Instead of
// Using empty
According to PHP.net the function addslashes() takes a String type as parameter. Check what type $value is. If it is an array itself then addslashes() may be throwing the error.
PS:
You should use $_POST[$key] rather than $_POST['$key'] if you want to use the value of $key as the index of the $_POST array.
I think you should use this code $_POST[$key] = $value; instead of using this $_POST['$key'] = trim(addslashes($value));
or make a check if the value is in array or not
Do this:
foreach ($_POST as &$value) {
$value = is_array($value) ?
array_map(function($x) { return trim(addslashes($x)); } :
trim(addslashes($value));
}
However, this could still fail if any of your parameters are multi-dimensional arrays. As mentioned in the comments, the right solution is to use prepared queries with parameters, rather than interpolating strings into SQL.

PHP Foreach() invalid argument

I'm receiving the fooling error below but not sure why. the $_Post all have data.
error: Warning: Invalid argument supplied for foreach() in /home/soc/process_member.php on line 19
$valid = true;
foreach($_POST['add'] && $_POST['cpl'] as $value) {
if(!isset($value)) {
$valid = false;
}
}
if(!$valid) {
$err .= 'please fill in all fields';
$en['reg_error'] = '<div class=err style="color: #FF0000;"><b>'._error.': '.$err.'</b></div><br>';
load_template('modules/members/templates/s_reg.tpl');
}
You should read more about PHP. There are two syntaxes for "foreach":
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
This is totally wrong:
foreach($_POST['add'] && $_POST['cpl'] as $value) {
Let me give you an example:
<?php
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
For more info, check the official PHP Documentation regarding foreach: http://php.net/manual/en/control-structures.foreach.php
I think what you want is a merged array:
foreach(array_merge($_POST['add'], $_POST['cpl']) as $value) {
// ...
First, in PHP, result of && operation is always boolean (i.e., true or false) - and you cannot supply it into foreach (and why you may wish to?), hence the error.
Second, even if it were possible, it'd still make little sense to use isset here: if either $_POST['add'] or $_POST['cpl'] is indeed unset, the notice is raised.
So, you can either just rewrite the first section of your code like this:
$valid = isset($_POST['add']) && isset($_POST['cpl']);
... or, taking into account the flexible nature of isset construct, just...
$valid = isset($_POST['add'], $_POST['cpl']);
... because, as said in its' official doc:
If multiple parameters are supplied then isset() will return TRUE only
if all of the parameters are set. Evaluation goes from left to right
and stops as soon as an unset variable is encountered.
If there's actually a whole big set of args to check and/or you're too lazy to type '$_POST' each time, use foreach to go through the array of their names (and not the actual values!) instead:
$valid = true;
foreach (array('add', 'cpl', 'whatever', 'it', 'takes') as $argName) {
if (! isset($_POST[$argName])) {
$valid = false;
break;
}
}

PHP local variable check

I am working with a set of variables that i check each time a page loads. I have successfully checked through $_REQUEST and $_SESSION, but am having trouble with the dynamci checking of variables assigned higher int he page, if they were set.
the following is my code:
$important_field = array('treatmentId','category','state','providerId','sellDoc','insuranceName','grossCharge','discount','allowable','patientPortion','insurancePortion','dateOfService','billFileLocation','eobFileLocation','fromTable');
foreach ($important_field as $key) {
if (!$$key || $$key == "none" || $$key == "" || $$key == NULL) {
if (!$_REQUEST[$key] || $_REQUEST[$key] == "" || $_REQUEST[$key] == NULL) {
if (!$_SESSION[$key]) {
// wow, guess it just wasn't set anywhere...
} else {
$user->sell->$key = $_SESSION[$key];
}
} else {
$user->sell->$key = $_REQUEST[$key]; $_SESSION[$key] = $_REQUEST[$key];
}
} else {
$user->sell->$$key = $$key; $_SESSION[$$key] = $$key;
}
}
Apparently evaluating $$key does not seem to do what i'm looking for as it never assigns the variable to the session... how should I be evaluating the $key to get the currently set value of say, field $eobFileLocation if it was already set in the PHP prior to the check?
Thanks,
Silver Tiger
Update:
ok, i have the following code, but there's still one bug with it. When i follow my process through af ew of these variables are set on each page and are carried over by the session variable as expected. The issue I am still having is that when i submit a new $_REQUEST variable which SHOULD change the session variable to the new submitted value, the script is finding a local variable ... where is it pulling $key and $$key from that is finding these as a local variable?
$important_field = array('treatmentId','category','state','city','providerId','sellDoc','insuranceName','grossCharge','discount','allowable','patientPortion','insurancePortion','dateOfService','billFileLocation','eobFileLocation','fromTable');
foreach ($important_field as $key) {
if (isset($$key) && !empty($$key) && $$key != "none") {
echo "Found local variable for ".$key.", i'll set the session and user to this.<br>\n";
$user->sell->$key = $$key;
$_SESSION[$key] = $$key;
} elseif (isset($_REQUEST[$key]) && !empty($_REQUEST[$key])) {
echo "Found submitted form variable for ".$key.", i'll set the session and user to this.<br>\n";
$user->sell->$key = $_REQUEST[$key];
$_SESSION[$key] = $_REQUEST[$key];
} elseif (isset($_SESSION[$key]) && !empty($_SESSION[$key])) {
echo "Found a session variable ".$key.", i'll set the user to this.<br>\n";
$user->sell->$key = $_SESSION[$key];
} else {
echo "There was no provided data for ".$key."<br>\n";
}
}
Any ideas why when i load the page it thinks the local (as listed above) is set? does $key and $$key read from $_SESSION['blah']/$_REQUEST['blah'] and think it's just $blah?
Are you sure this is what you want:
$user->sell->$$key = $$key;
should it not be
$user->sell->$key = $$key;
try using the empty function:
if (empty($$key) || $$key == "none")
if (empty($_REQUEST[$key]))
and the isset function:
if (!isset($_SESSION[$key]))
it is
$user->sell->$key = $$key;
not
$user->sell->$$key = $$key;
and
$_SESSION[$$key]
should be
$_SESSION[$key]
You're messing with your variables, this is not good. In fact, using two var signs ($$) describes a "variable variable".
$foo = "name";
$$foo = "value";
So you expect the following:
echo $foo; // => "name"
echo $$foo; // => "value"
What you maybe are not expecting, is:
echo $name; // => "value"
So you're better off cleaning up your code first.
Well, I have expressed my concerns about the cleanliness of this approach in the comments. Here's at least some more compact code without variable variables to do the same thing:
$keys = array('treatmentId', 'category', ...)
$values = array_filter(array_merge(
array_intersect_key($_SESSION, array_flip($keys)),
array_intersect_key($_REQUEST, array_flip($keys)),
compact($keys)
), function ($v) { return $v && $v != 'none'; });
$_SESSION = array_merge($_SESSION, $values);
foreach ($values as $key => $value) {
$user->sell->$key = $value;
}
// For debugging purposes:
//
// $diff = array_diff_key(array_flip($keys), $values);
// if ($diff) {
// 'No values for ' . join(', ', array_keys($diff));
// }

error during addslashes() function in php

html form code-
<td width="75">
<input name="txtQty[]" type="text" id="txtQty[]" size="5"
value="<?php echo $ct_qty; ?>" class="box" onKeyUp="checkNumber(this);">
when I submit form I calls following script-
if (!get_magic_quotes_gpc()) {
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(addslashes($value));
}
}
if (isset($_GET)) {
foreach ($_GET as $key => $value) {
$_GET[$key] = trim(addslashes($value));
}
}
}
error-
Warning: addslashes() expects parameter 1 to be string, array given in C:\xampp\htdocs\shizin\products\library\config.php on line 53
I think this script is being used just to trim input but I dont know what this addslash function does and why this error coming.
If you apply this code on an int value then you remove these function like this
if (!get_magic_quotes_gpc()) {
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
$_POST[$key] = $value;
}
}
if (isset($_GET)) {
foreach ($_GET as $key => $value) {
$_GET[$key] = $value;
}
}
}
The whole approach is wrong.
Upon receiving user supplied data you have to strip slashes, added by magic quotes, not add.
About array approach it says 2 answers already posted, I hope it is well explained here.
Not so well, but anyway.
So, you will need 2 code snippets.
A first one is stripslashes_deep() from http://www.php.net/manual/en/function.stripslashes.php
A second one you will get after you tell us, why did you think you need the code you posted.
the error said , the addslashes function try to Quote string with slashes ,
but the $value the parameter is not a string is an array,
what CONTAIN the $_GET ?
its because that the page that call to this script pass a array . txtQty[]
http://php.net/manual/en/function.addslashes.php
Just echo $value before passing it to addslashes(), then you should see the problem immediately.

Categories