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.

10
  • 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") Commented Apr 12, 2017 at 9:10
  • you can first try with simple form, just file and then check via print_r($_FILES); Commented Apr 12, 2017 at 9:10
  • print_r($_FILES); returns empty array. Though I change name= "file" still getting empty array. @OldPadawan Commented Apr 12, 2017 at 9: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); } Commented Apr 12, 2017 at 9:18
  • 1
    This checklist might help: stackoverflow.com/questions/3586919/… Commented Apr 12, 2017 at 9:26

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

5 Comments

getting file name and everything by this code. but whats wrong with my code then
did you try <?php if ($_POST) { var_dump($_FILES); } ?> just on the top of your addPost.php ?
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
well.... I had to do all the work! Just add <script>$("#postForm").validate();</script> in your file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.