2

Can you please take a look at this snippets and let me know what I am doing wrong to upload image to the img folder in the root directory?

I have simple inputs template like

Bug Title:<br>
<input type="text" name="bugTitle">
Bug Description: 
<textarea name="bugDescriotion"></textarea>
Bug Image:<br>
<input type="file" id="input" name="bug-img">

and a jquery Ajax request like

 $("#submit-bug").on("click", function(e) {
     var mdata = new FormData();
     mdata.append('bug_title', $('input[name=bugTitle]').val());
     mdata.append('bug_description', $('input[name=bugDescriotion]').val());
     mdata.append('bug_img', $('input[name=bug-img]')[0].files[0]);

     e.preventDefault();
     var request = $.ajax({
         type: "POST",
         url: "loadBugs.php",
         data: mdata,
         cache: false,

         processData: false,
         beforeSend: function() {
             console.log(mdata);
         }
     });

     request.done(function(data) {
         console.log(data);
     });

     request.fail(function(jqXHR, textStatus) {
         console.log("Request failed: " + textStatus);
     });

 });

and eventually a php filr called loadBugs.php

<?php
header('Content-type: application/json');
$validextensions = array("jpeg","jpg", "png");
$temporary       = explode(".", $_FILES["bug_img"]["name"]);
$file_extension  = end($temporary);
if ((($_FILES["bug_img"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 100000) //Approx. 100kb files can be uploaded.
    && in_array($file_extension, $validextensions)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
    } else {
        if (file_exists("img/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
        } else {
            $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
            $targetPath = "img/" . $_FILES['file']['name']; // Target path where file is to be stored
            move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
            echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
        }
    }
} else {
    echo "<span id='invalid'>Invalid file Size or Type<span>";
}

?>
6
  • What errors are you getting? Did you try to debug this code? Commented Sep 15, 2015 at 22:30
  • I would recommend taking AJAX out of the picture and insure your html form and php script are working correctly. Once you can get a file into the folder using just html and php, then add in the AJAX. A parse error is typically a syntax error somewhere in your code. Commented Sep 15, 2015 at 22:34
  • if it's on the screen it should be a php error. AJAX doesn't output errors to the screen in general. Commented Sep 15, 2015 at 22:36
  • try adding also contentType: false, to your ajax. Commented Sep 16, 2015 at 2:01
  • Thanks Ozan , I add the contentType: false, but no success! in the console I am getting a html format of error page Commented Sep 16, 2015 at 2:08

1 Answer 1

1
<?php   $validextensions = array("jpeg","jpg", "png");
    $type = ["image/png","image/jpg","image/jpeg"];
    $file_extension  = pathinfo($_FILES["bug_img"]["name"], PATHINFO_EXTENSION);
        if(!in_array($_FILES["bug_img"]["type"],$type)){
            die("Wrong File type");
        }
        if ($_FILES["file"]["size"] < 100000) {
            die("Size not Allowed");}
        if(!in_array($file_extension, $validextensions)) {
            die("FILE EXTENSION NOT ALLOWED");
        }
        if ($_FILES["file"]["error"] > 0) {
                die( "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>");
        }
        if (file_exists("img/" . $_FILES["file"]["name"])) {
            die($_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ");
        }
            $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
            $targetPath = "img/" . $_FILES['file']['name']; // Target path where file is to be stored
        if(move_uploaded_file($sourcePath, $targetPath)){
            echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
        }
                    ?>

First of all your content type

header('Content-type: application/json');

is wrong, you are not returning json.

Second of all, you should check dev Tools to see what you are sending and receiving. (I didn't try it, but it should work) Third, File EXTENSION should be checked with PathINFO instead of explode.

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

2 Comments

Thanks Elias I but need to use the header('Content-type: application/json'); since I am going to retrieve some data from database in the rest of the snippet and display them on page
Then all those html "error" you should change it to json with json_encode()

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.