Reputation: 11
I have trouble sanitizing my array and am hoping someone can take a look!
here is my input:
<input type="text" name="courseno[]" id="courseno" size="12" />
here is my function to sanitize my data:
function sanitizeData ($datastring) {
if (is_array($datastring)) {
foreach ($datastring as $indivdata) {
$indivdata = sanitizeData($indivdata);
}
}
else {
$datastring=trim($datastring);
$datastring=htmlspecialchars($datastring);
$datastring = mysql_real_escape_string($datastring);
return $datastring;
}
}
if (isset($_POST['courseno'])) {
$courseno = sanitizeData($_POST['courseno']);
}
the $courseno
data won't post when I try to sanitize the array, while all my other data gets posted. When I don't sanitize $courseno
, the data gets posted to the database just fine.
Upvotes: 1
Views: 121
Reputation: 28177
In your if (is_array($datastring))
test, you assign the output of the sanitizeData
call back to $indivData
. So if the input contains an array, a real value is never returned. $courseno
will be assigned a NULL value. You'd probably want to change it to something along the lines of this:
function sanitizeData ($datastring) {
if (is_array($datastring)) {
$result = '';
foreach ($datastring as $indivdata) {
$result .= sanitizeData($indivdata);
}
return $result;
}
else {
$datastring=trim($datastring);
$datastring=htmlspecialchars($datastring);
$datastring = mysql_real_escape_string($datastring);
return $datastring;
}
}
if (isset($_POST['courseno'])){
$courseno = sanitizeData($_POST['courseno']);
}
Upvotes: 1
Reputation: 9148
It is just a variable scope problem.
function sanitizeData ($datastring) {
// This is needed to hold the value between function calls ...
static $indivdata = array();
if (is_array($datastring)) {
foreach ($datastring as $indivdata) {
$indivdata[] = sanitizeData($indivdata);
}
return $indivdata;
}
else {
$datastring=trim($datastring);
$datastring=htmlspecialchars($datastring);
$datastring = mysql_real_escape_string($datastring);
return $datastring;
}
}
// $courseno will be an array now.
if (isset($_POST['courseno'])){
$courseno= sanitizeData($_POST['courseno']);
}
Unless I missed something at this late hour, it seems your function does not return the data array. There are a couple of ways to solve this, but the above code should get you in the right track.
Upvotes: 0
Reputation: 526543
Well, it would help if sanitizeData()
returned a value when $datastring
is an array.
if (is_array($datastring)) {
foreach ($datastring as $indivdata) {
$indivdata = sanitizeData($indivdata);
}
// you need to actually return something here
}
Upvotes: 1