I have made a little script that allows a user to choose how many files they want to upload by making a selection in a <select> box. When they make a selection, the specified number of file imputs are added.
The code is like so:
<form action="uploaded_pics.php" method="post" id="formie" enctype="multipart/form-data">
<select name="numPics" onchange="reload(this.form)">
<option selected value="">Select </option>
var parent = document.getElementById('formie');
var numPics = form.numPics.options[form.numPics.options.selectedIndex].value;
for (i=1; i <=numPics; i++)
var label = document.createElement('LABEL');
label.appendChild(document.createTextNode('Select a photo: '));
var field = document.createElement('INPUT');
field.type = 'file';
field.name = 'ufile';
var formField = document.createElement('DIV');
var submitBtn = document.createElement('INPUT');
submitBtn.type = "submit";
submitBtn.value = "Upload";
I then am checking the results of this in "uploaded_pics.php" like so:
foreach ($_POST as $key => $value)
echo "Key is: " . $key;
echo "Value is: " . $value . "<br />";
I'm not 100% sure of exactly what is happening to produce the problem I'm having, but basically even though the file inputs appear in the form as expected, they subsequently don't show up in the $_POST array on submit.
However, if I remove the line
field.type = 'file';
(and therefore make text inputs), they do show up in the $_POST array.
I'm hoping someone can shed some light on this! I've tried Googling it, but haven't turned up any results - possibly because I'm not quite sure what I'm even looking for.
Any help would be much appreciated.
I've worked out what the problem is now - I'm embarrassed to admit it as it's another brain freeze moment - I was trying to get the file names like so $FILES['ufile']['name']; which of course is going to give me nothing, as I need to be asking for $FILES['ufile']['name'][$i] (blushes and avoids eye contact). Still, I've learnt an important lesson about doing work on a Friday afternoon and have resolved to avoid it in future wherever possible
File upload fields don't appear in the PHP
$_POST array. An uploaded file could be several gigabytes!
You can use the
$_FILES superglobal, and/or a few related built-in functions. See Handling file uploads for an overview of handling file uploads in PHP.