-4

The code analyzes if the file you input is a supported file type and size and lets you upload files without upload button. I am trying to make this code be able to upload multiple files. I tried using for loop, but it does not work. There should also be a file for the mysql connection and it should be included at the PHP file, but I cannot add it because it says my post is mostly code and I should add more details. Help please.

HTML

 <form action="upload.php" enctype="multipart/form-data" method="post" id="files" hidden="true">
                                <input type="file" name="files[]" id="file" multiple>
                                <input type="button" class="btn btn-primary btn-sm" onClick="file.click();" value="Upload File" id="uploadbtn" />
                            </form>

//Javascript
      
function insertData(data, path) {
                    //  #file id will trigger once clicked and insert the file
                    $("#file").on("change", function() {

                        var name = document.getElementById("file").files[0].name;
                        var form_data = new FormData();
                        var ext = name.split('.').pop().toLowerCase();
                        //validation
                        if (jQuery.inArray(ext, ['png', 'jpg', 'jpeg', 'mp4', 'ogg', 'webm', 'pdf', 'docx', 'doc', 'xlsx', 'csv', 'ppt', 'pptx', 'rar', 'zip'
                            ]) == -1) {
                            alert("Error: This file is not supported. The supported file types are: png, jpg, jpeg, mp4, ogg, and webm for media, pdf, docx, doc, xlsx, csv, ppt, pptx, rar, and zip for documents.");
                            location.reload();
                        } else { 
                            var oFReader = new FileReader();
                            oFReader.readAsDataURL(document.getElementById("file").files[0]);
                            var f = document.getElementById("file").files[0];
                            var fsize = f.size || f.fileSize;
                            if (noParent == false) {
                                selectedID = "#";
                            } else {
                                selectedID = data;
                            }
                            if (fsize > 50000000) {
                                alert("Error: This file size is too large to upload. The maximum supported file size is 50 MB.");
                                location.reload();
                            } else if (selectedID != undefined && selectedID != "") {
                                //   getting the data from UI form
                                form_data.append("file", document.getElementById('file').files[0]);
                                form_data.append("selectedID", selectedID);
                                form_data.append("path", path);

                                // ajax call for sending data to php file and use it for inserting on mysql database
                                $.ajax({
                                    url: "AddCA.php",
                                    method: "POST",
                                    data: form_data,
                                    contentType: false,
                                    cache: false,
                                    processData: false,
                                    beforeSend: function() {

                                    },
                                    success: function(data) {
                                        //   redirection to refresh the file tree
                                        location.reload();
                                    }
                            });}
                        }
                    });
                    
                };

PHP

    if (isset($_FILES["file"]["name"]) || isset($_POST["selectedID"])) {
        $selectedID = $_POST["selectedID"];
        $path = $_POST["path"];
        $filetype = "file";
        if ($selectedID == "") {
            $selectedID = "#";
        }

        $text = $_FILES["file"]["name"];
        $filesize = $_FILES["file"]["size"];
        $test = explode('.', $_FILES["file"]["name"]);
        $ext = end($test);
        $name = rand(100, 999) . '.' . $ext;
        $location = './upload/' . $text;
        move_uploaded_file($_FILES["file"]["tmp_name"], $location);

        $getExt = explode(".", $text);
        $fileExt = end($getExt);

        // condition for setting up the icon of file
        if (strtolower($fileExt) == "png" || strtolower($fileExt) == "jpeg" || strtolower($fileExt) == "jpg" || strtolower($fileExt) == "png" /*|| strtolower($fileExt) == "gif"*/) {
            $icon = "fa-sharp fa-solid fa-image";
        } elseif (strtolower($fileExt) == "pdf") {
            $icon = "fa-sharp fa-solid fa-file-pdf";
        } elseif (strtolower($fileExt) == "docx" || strtolower($fileExt) == "doc") {
            $icon = "fa-sharp fa-solid fa-file-word";
        } elseif (strtolower($fileExt) == "xlsx" || strtolower($fileExt) == "csv") {
            $icon = "fa-sharp fa-solid fa-file-excel";
        } elseif (strtolower($fileExt) == "ppt" || strtolower($fileExt) == "pptx") {
            $icon = "fa-sharp fa-solid fa-file-powerpoint";
        } elseif (strtolower($fileExt) == "rar" || strtolower($fileExt) == "zip") {
            $icon = "fa-sharp fa-solid fa-file-zipper";
        } elseif (strtolower($fileExt) == "mp4" || strtolower($fileExt) == "ogg" || strtolower($fileExt) == "webm") {
            $icon = "fa-sharp fa-solid fa-video";
        } elseif ($filetype == "file" && strtolower($fileExt) == "") {
            $icon = "fa-sharp fa-solid fa-file";
        } else {
            $icon = "fa-sharp fa-solid fa-folder";
        }

        //inserting the file on database
    $sql = "INSERT INTO ca_tb(newid,text,parent,size,a_attr,icon,path) VALUES((select auto_increment from information_schema.TABLES where TABLE_NAME ='ca_tb' and TABLE_SCHEMA='filehub'),'$text','$selectedID','$filesize', '$filetype', '$icon', '$path')";
        mysqli_query($con, $sql);

        $sql2 = "INSERT INTO users_activity (user_id, date, fname, activity) 
        VALUES ('$userid', '$date', '$fname', 'uploaded: $text located in $path')";
        mysqli_query($con, $sql2);
        mysqli_close($con);
        
    }
  • 2
    You'll need a loop both in the JS and the php side. It's unclear what you tried or what went wrong. Please post your attempt and a more specific problem description than "does not work " then we can understand the exact issue, rather than expecting us to start all over again. See also [ask] and how to make a [mre] of your issue. You can [edit] your post. Thanks – ADyson Sep 01 '23 at 05:33
  • 1
    Is this a JS problem, a PHP problem, or a MySQL problem? What have you tried to resolve it? Where are you stuck? Also, keep in mind that your `INSERT` query is highly vulnerable for SQL injection. Have a look at prepared statements to avoid getting hacked – Nico Haase Sep 01 '23 at 06:11
  • P.S. It's not like this has never been solved before...you can take inspiration from [previous examples](https://www.google.com/search?q=Upload+multiple+files+using+JQuery%2C+PHP+and+HTML) – ADyson Sep 01 '23 at 06:45
  • 1
    P.P.S. **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unparameterised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Sep 01 '23 at 07:11
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use that resource again. – ADyson Sep 01 '23 at 07:11

0 Answers0