I am using the following HTML & PHP code to move multiple images to my server.
Is there a way using my code that I can associate a specific input element with the uploaded file?
So in my for loop, I can discover when the image from ‘image_22‘ is being processed. Is this possible using my current code?
Dream world would be storing the value “image_22” inside a variable $imageNum 🙂
Here is a snippet of what I’m currently working with…
HTML:
<input id="image_22" name="images[]" type="file" />
<input id="image_8" name="images[]" type="file" />
...
PHP:
<?php
if (isset($_POST['Submit'])) {
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
/**
* we get a $_FILES['images'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['images']);
*/
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['images']['name'][$i];
if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory .
$_FILES['images']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of File fields created $number_of_file_fields.<br/> ";
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
}
?>
Thank you!!
In your HTML, just include that value inside the
[].In your loop, instead of an incremental for loop, use a
foreachwith index, which is a more common pattern in PHP than the incremental type. The$indexwill be the number supplied in the[]:Note that your script is currently vulnerable to path injection attacks. You must filter the
nameof each file against the inclusion of things like../which could force the file to be saved anywhere on your filesystem (writable by the web server)! It is recommended to check the name with a regular expression of acceptable values: