0

I'm trying to print the name of multiple files but uploaded array gives me nothing. What can I do?

<?php
    if (!empty($_FILES['file'])) {
        foreach ($_FILES['file']['name'] as $key => $name) {
            if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")) {
                $uploaded[] = $name;
            }
        }
        print_r($uploaded);
    }
?>

<!doctype html>

    <body>
        <div>
            <form action="" method="post" encype="multipart/form-data">
                <div>
                    <input type="file" name="file[]" multiple="multiple">
                    <input type="submit" value="Upload">
                </div>
            </form>
        </div>  
    </body>
Ahmed Siouani
  • 13,701
  • 12
  • 61
  • 72
rexhin
  • 17
  • 4

1 Answers1

0

I would recommend refactoring your code like this; note the addition of two array_key_exists checks as well as an $uploaded = array(); to init the $uploaded array before the loop:

<?php
    if(!empty($_FILES['file'])) {
        $uploaded = array();
        if (array_key_exists('name', $_FILES['file'])) {
            foreach($_FILES['file']['name'] as $key => $name) {
                if(array_key_exists('error', $_FILES['file']) $_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")) {
                    $uploaded[] = $name;
                }
            }
        }
        print_r($uploaded);
    }
?>

But I would also recommend doing a very basic debugging check right at the beginning of the code to see if $_FILES has anything in in:

<?php
    echo '<pre>';
    print_r($_FILES);
    echo '</pre>';
    if(!empty($_FILES['file'])) {
    …

But looking at your HTML file, your <form action="" is empty:

<form action="" method="post" encype="multipart/form-data">

What happens if you change that to:

<form action="#" method="post" encype="multipart/form-data">

Or even get rid of the action entirely:

<form method="post" encype="multipart/form-data">

I think that is the issue since your form is in HTML5 and the action="" is set, it’s never going to work. Specifically as outlined in the HTML5 spec:

The action and formaction content attributes, if specified, must have a value that is a valid URL potentially surrounded by spaces.

Community
  • 1
  • 1
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103