Search code examples
phpparametersstripslashes

How to fix stripslashes() expects parameter 1 to be string when also using array


I have a php form that passes values to an email. The form has both single values and arrays. I'm getting the following error and I can't fix it.

Warning: stripslashes() expects parameter 1 to be string, array given in /home/...... line 147

If tried to add

if(is_array$cleanvalue = stripslashes($value);

Line 147 is as follows:

#clean fields for repost or display
foreach ($_POST as $key=>$value) {
$cleanvalue = stripslashes($value);
$repostvalue = stripquotes($cleanvalue);
$hiddenhtml .= "<input type=\"hidden\" name=\"$key\" 
value=\"$repostvalue\">\n";
${$key} = $cleanvalue;
}

Upon submitting the form, I get the following error, but not until the entire form is filled out. Warning: stripslashes() expects parameter 1 to be string, array given in /home/...... line 147


Solution

  • You could try using is_array() and mapping stripslashes() on each value if it is:

    foreach ($_POST as $key=>$value) {
        if (is_array($value)) {
            ${key} = array_map('stripslashes', $value);
        } else {
            $cleanvalue = stripslashes($value);
        } 
    
        $repostvalue = stripquotes($cleanvalue);
        $hiddenhtml .= "<input type=\"hidden\" name=\"$key\" value=\"$repostvalue\">\n";
        ${$key} = $cleanvalue;
    }
    

    It looks like stripquotes() may be a custom function? You'll need to modify it similarly. You will need to loop over your values differently if you want to output them in html again, maybe something like this:

    foreach ($_POST as $key=>$value) {
        if (is_array($value)) {
            ${key} = array_map('stripslashes', $value);
        } else {
            $cleanvalue = stripslashes($value);
        } 
    
        $repostvalue = stripquotes($cleanvalue);
    
        if (is_array($value))
        {
            foreach($repostvalue as $repost) {
                $hiddenhtml .= "<input type=\"hidden\" name=\"$key[]\" value=\"$repost\">\n";
            }
    
        } else {
            $hiddenhtml .= "<input type=\"hidden\" name=\"$key\" value=\"$repostvalue\">\n";
        }
    
        ${$key} = $cleanvalue;
    }