0

I want to upload a file to server.I have added all the code to upload file to server but the $_FILES array is empty. File Value is not getting set in an array.

I have done same code for another web page and it works fine, but not getting whats the issue in this.

I have set the enctype as multipart/form-data but still its giving empty array.

html file:

     <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Post</title>
</head>
<body>

<script>

</script>

<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">

    <fieldset>
        <legend>Please add the details below </legend>
        <p>
            <label for="title">Title (required, at least 2 characters)</label>
            <input id="title" name="title" minlength="2" type="text" required>
        </p>

        <p>
            <label for="desc">Description (required, at least 2 characters)</label>
            <input id="desc" name="desc" minlength="2" type="text" required>
        </p>
        <p>
            <label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
            <input id="keywords" name="keywords" minlength="2" type="text" required>
        </p>

        <select id="types" name="types" onchange="myFunction(this)">

            <option value="">Select type</option>

            <option value="2">Add Link</option>
            <option value="0">Upload Image</option>
            <option value="1">Upload Video</option>

        </select><br><br>

        <div id="link" style="display: none">

        <p>
            <label for="url">URL (required)</label>
            <input id="url" type="url" name="url" required>
        </p>

        <p>
            <label for="urlType">Select Url Type :(required)</label>
            <select name="urlType" id="urlType">
                <option value="">Select Url Type...</option>
        <!--        <option value="0">Server Image</option>
                <option value="1">Server Video</option>-->
                <option value="2">YouTube Video</option>
                <option value="3">Vimeo Video</option>
                <option value="4">Facebook Image</option>
                <option value="5">Facebook Video</option>
                <option value="6">Instagram Image</option>
                <option value="7">Instagram Video</option>
                <option value="-1">Other</option>
            </select>
        </p>

        </div>

        <div id="filediv" style="display: none">

            Select file to upload:
            <br><br>
            <input name = "file" type="file" id="fileToUpload"><br><br>

        </div>


        <p>
            <label for="postType"> Select Post Type :(required)</label>
            <select name="postType" id="postType">
                <option value="">Select Post Type...</option>
                <option value="0">Normal</option>
                <option value="1">Featured</option>
                <option value="2">Sponsored</option>
            </select>
        </p>
        <p>
            <label for="category"> Select Category :(required)</label>
            <select name="category" id="category">
                <option value="">Select Category...</option>
            </select>
        </p>
        <p>
            <input type="hidden" name="action_type" id="action_type_id"/>
            <input type="hidden" name="id" id="p_id"/>
<!--            <a href="javascript:void(0);" class="btn btn-warning" onclick="$('#postForm').slideUp();">Cancel</a>
            <a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add User</a>-->
           <input type="submit" name="submit" id="submit" value="Submit">
        </p>
    </fieldset>

    <div class="result" id="result"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
    <script>

        function myFunction(obj) {

            var type = obj.value;
            var x = document.getElementById('link');
            var y = document.getElementById('filediv');


            if(type == "2")
            {
                x.style.display = 'block';
                y.style.display = 'none';
            }
            else {
                x.style.display = 'none';
                y.style.display = 'block';
            }

        }

    </script>
</form>
</body>
</html>

addPost.php

    <?php

include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);

if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {

    if($_POST['action_type'] == 'add') {
         $database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
        $dbConnection = $database->getDB();
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbConnection->prepare("insert into keywords(keyword) 
                                    values(?)");
        $stmt->execute(array($_POST['keywords']));

        $file_result = "";

        if(strcmp($_POST['types'],"2") == 0)
        {

            //insert data into posts table
            $stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type) 
                                    values(?,?,?,?,?,?,?)");
            $stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));

            $count = $stmt->rowCount();

            if ($count > 0) {

                echo "Post submitted.";
            } else {

                echo "Could not submit post.";
            }


        }
        else {

            if(isset($_POST['submit'])){

                print_r($_FILES);

                if (isset($_FILES["file"]["name"])) {


                    $file_result = "";

                    if ($_FILES["file"]["error"] > 0) {
                        $file_result .= "No file uploaded or invalid file.";
                        $file_result .= "Error code : " . $_FILES["file"]["error"] . "<br>";
                    } else {

                        if (strcmp($_POST['types'], "0") == 0) {
                            $target_dir = "AgTv/images/";
                        } else {
                            $target_dir = "AgTv/videos/";
                        }

                        $newfilename = preg_replace('/\s+/', '',
                            $_FILES["file"]["name"]);
                        $target_file = $target_dir . basename($newfilename);

                        /*$target_file = $target_dir . basename($_FILES["file"]["name"]);*/

                        $file_result .=
                            "Upload " . $_FILES["file"]["name"] . "<br>" .
                            "type " . $_FILES["file"]["type"] . "<br>" .
                            "temp file " . $_FILES["file"]["tmp_name"] . "<br>";


                        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {

                            $stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type) 
                                    values(?,?,?,?,?,?,?)");
                            $stmt->execute(array($_POST['category'], $_POST['title'], $newfilename, $_POST['types'], $_POST['desc'], $_POST['keywords'], $_POST['postType']));

                            $count = $stmt->rowCount();

                            if ($count > 0) {

                                echo "The file " . basename($_FILES['file']['name']) . " has been uploaded, and your information has been added to the directory";

                            } else {

                                echo "Could not submit post.";
                            }

                        }
                    }

                }
                else{

                    echo 'empty file';
                }
            }
        }

    }

}

?>

Can anyone help please? Thank you.

Sid
  • 2,792
  • 9
  • 55
  • 111
  • what does return `print_r($_FILES);` ? and what happens if you run the code only from `print_r($_FILES);` ? any error reported ? (even though it shouldn't really mess, get rid of blank in input `name = "file"`) – OldPadawan Apr 12 '17 at 09:10
  • you can first try with simple form, just file and then check via print_r($_FILES); – Mubashar Iqbal Apr 12 '17 at 09:10
  • print_r($_FILES); returns empty array. Though I change name= "file" still getting empty array. @OldPadawan – Sid Apr 12 '17 at 09:15
  • your html files seems ok, try to var_dump $_FILES just before any other logic, what it give you back? if ($_POST) { var_dump($_FILES); } –  Apr 12 '17 at 09:18
  • i see on your html form, you show and hide div for file upload. Check your network tab in your browser and see if the file is being sent atleast – Rotimi Apr 12 '17 at 09:23
  • 1
    This checklist might help: http://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php#3587158 – Fabian Horlacher Apr 12 '17 at 09:26
  • I tried to make another html form only with file input and same add.php form for this I am getting error as Warning: POST Content-Length of 8933051 bytes exceeds the limit of 8388608 bytes in Unknown on line 0. I tried to set max size programatically ini_set('post_max_size', '500M'); ini_set('upload_max_filesize', '500M'); also I have set uploadMax size as 100M in php.ini development file. @MubasharIqbal – Sid Apr 12 '17 at 09:38
  • how to check if file is being sent? @Akin – Sid Apr 12 '17 at 09:39
  • I checked by var_dump($_FILES); I get result as array(0) { } @GiacomoPittalis – Sid Apr 12 '17 at 09:42
  • But I also tried this file upload for other pages its not giving any error for file size though I have not set the ax upload or post size. . – Sid Apr 12 '17 at 09:43

1 Answers1

1

UPDATED WITH SOLUTION: just add

<script>
        $("#postForm").validate();
</script> 

below the inclusion of jquery.validate.min.js. You $_FILES array is working fine, you are just not sending the post at all!

  • getting file name and everything by this code. but whats wrong with my code then – Sid Apr 12 '17 at 10:00
  • did you try just on the top of your addPost.php ? –  Apr 12 '17 at 10:02
  • 1
    ok, I've done a quick test, you have an error on your validation, I just tried to remove all the "required" attributes in your code and it seems to work fine. Try to fix it –  Apr 12 '17 at 10:09
  • well.... I had to do all the work! Just add in your file. –  Apr 12 '17 at 10:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/141536/discussion-between-sid-and-giacomo-pittalis). – Sid Apr 12 '17 at 10:26