Search code examples
phparraysstring

Function which sanitizes string is treating my data as an array


I have a cart php page where I display the client products. In the same page I have a form that sends the client personal details such as name, surname, etc., but also the product info such as product name, qty, etc. directly to my email address.

Now, the problem is that when I send the form, on my email address I receive all the info, but not the product details, for example on the product name field in the order email I have ARRAY.

I see there is a problem converting array to string but I don't know how, I've tried a few examples but none of them worked. Bellow I've put my codes that I think are my problem.

echo '<input type="text" name="name1" id="name1">';
echo '<input type="email" name="email1" id="email1">';
         
echo '<input type="hidden" name="product_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items++;
echo '<input type="submit" value="submit">';
function clean_string($string) {
    $bad = array("content-type", "bcc:", "to:", "cc:", "href");
    return str_replace($bad, "", $string);
    $product_name_string = implode(" ", $cart_items);
}
     
$email_message .= "Nume: " . clean_string($name1) . "\n";

$email_message .= "E-mail: " . clean_string($email1) . "\n";

$email_message .= "Cos: " . clean_string($product_name_string) . "\n";

Solution

  • Basic PHP: An array used in string context will simply be the literal word Array.

    e.g.

    $foo = array('a', 'b', 'c');
    echo $foo;
    

    will print the word Array, not a,b,c or whatever.

    You're telling PHP your input fields are to be treated as arrays:

    <input type="text" name="item_code[foo]" ...
                                      ^---^----
    

    so $_POST['item_code'] will itself be an array. If you want the CONTENTS of those arrays to be present in your email, then have something like:

    $item_codes = implode(',', $_POST['item_code']);