Sun Z Sun Z - 1 year ago 57
PHP Question

Passing an array to another page (Form)

I have the following array and form on page1.php:

$my_array = array("Volvo", "BMW", "Toyota");

echo " <form id=\"my_form\" action=\"page2.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"id\" value=\"10\">
<input type=\"hidden\" name=\"input_name\" value=\"".serialize($my_array)."\" />

<a href=\"javascript:{}\" onclick=\"document.getElementById('my_form').submit(); return false;\">Send</a> </form>";

On the page2.php I want to print_r the array:

$id = $_POST['id'];
$passed_array = unserialize($_POST['input_name']);


Why I can't receive my_array on page2? I can't see the mistake I made!

PS: I received id on page2.

Answer Source

i'm glad @ksealey pointed out a more proper method of doing this, but for the sake of answering the question...the reason it's not working is that the serialize alone is not enough to prevent the invalid html. see result of what the serialize leaves in the html:

enter image description here

so you need to be sure the html you produce is valid. you might use encoding like base64 to produce safe html:

echo  " <form id=\"my_form\" action=\"\" method=\"post\"";
echo "enctype=\"multipart/form-data\">";
echo "<input type=\"hidden\" name=\"id\" value=\"10\">";
echo "<input type=\"hidden\" name=\"input_name\" ";

echo "value=\"".base64_encode(serialize($my_array))."\" />";

enter image description here

then you can just add the decode to your output:

$passed_array = unserialize(base64_decode($_POST['input_name']));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download