0

I have the following files. Nothing is displayed in the Response header of developer tools. I am expecting the variables related to files and post in my accept.php page.

I can see console.log(formData); getting printed but console.log(returndata);

1) send.php file

<?php

echo ' 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script type="text/javascript" src="file.js"></script>

<form id="data" enctype="multipart/form-data">
      <input type="hidden" name="id" value="123" readonly="readonly">
      User Name: <input type="text" name="username" value=""><br />
      Profile Image: <input name="profileImg[]" type="file" /><br />
      Display Image: <input name="displayImg[]" type="file" /><br />
      <button  type = "button" onclick="submitFileTest()">Submit Button  </button>
    </form>';

?>

2) file.js

function submitFileTest() { 


          //grab all form data  
          var formData = new FormData($(this)[0]);

          console.log("Form Data Test");
          console.log(formData);

          $.ajax({
            url: 'accept.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
              //alert(returndata);
              console.log(returndata);
            }
          });




 }

3) accept.php

<?php


        if (isset($_POST['id'])) {                      
            $id = $_POST['id'];
            var_dump($id);
            echo $id;
        }


        if (isset($_POST['username'])) {
           $username = $_POST['username'];
           var_dump($username);
           echo $username;
        }


        if (isset($_FILES['profileImg'])) {
            $profileImg = $_FILES['profileImg'];
            var_dump($profileImg);
            echo $profileImg;
        }

        if (isset($_FILES['displayImg'])) {
             $displayImg = $_FILES['displayImg'];
             var_dump($displaying);
             echo $displayImg;
        }

?>

TESTING RESULTS (after using Popmedic answer):

Before testing, for displayImg,I changed the file array value in the following line formData.append('displayImg', $('input[type=file]')[1].files[0]); from 0 to 1 as shown below formData.append('displayImg', $('input[type=file]')[1].files[1]);

I am able to see the id value, username value and profileImg value in my php script as shown in the screenshot of console window of IE11 below. But for some reason, the code is not picking up the second file which is displayImg.

enter image description here

The following is the screenshot of Request body of IE11 showing that for the file displayImg, there is nothing present.

enter image description here

Clarifications on Popmedic's comments (April 18):

I have merged the POST and FILEs results using this solution and got the following in the JSON format:

{"id":"123","username":"123","profileImg":{"name":"Request_body.PNG","type":"image\/png","tmp_name":"C:\\wamp\\tmp\\phpA981.tmp","error":0,"size":15842},"displayImg":{"name":"Request_body.PNG","type":"image\/png","tmp_name":"C:\\wamp\\tmp\\phpA9A1.tmp","error":0,"size":15842}}

I already have a Java webservice working which is accepting a JSON object and storing it in the Oracle database in the form of CLOB. So that's the reason I merged and converted into JSON as shown above. I would like to include the variable $str value also in the JSON response above obtained from this line of code$str = file_get_contents($_FILES["displayImg"]["tmp_name"]); so that in addition to the above JSON, I could also include the file contents to the webservice and that Java webservice will make sure that it's inserted into the Oracle database. eventually my cuRL request would look like this:

                      $curl = curl_init();
                      curl_setopt_array($curl, array(
                      CURLOPT_PORT => "9090",
                      CURLOPT_URL => "http://localhost:9090/myJavaWebservice/rest/somepath/insertDataToDB",
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_ENCODING => "",
                      CURLOPT_MAXREDIRS => 10,
                      CURLOPT_TIMEOUT => 30,
                      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                      CURLOPT_CUSTOMREQUEST => "POST",
                      CURLOPT_POSTFIELDS => $_POST["myData"],
                      CURLOPT_HTTPHEADER => array(
                        "Cache-Control: no-cache",
                        "Content-Type: application/json"

                        ),
                      ));

                    $response_post_march22 = curl_exec($curl);
                    $err = curl_error($curl);

                    curl_close($curl);

                    if ($err) {
                      echo "cURL Error #:" . $err;
                    } else {
                      echo $response_post_march22;
                    } 

I already have the above curl request working and inserting the data into the database but now instead of myData which is a JSON object, I would be passing the new JSON, I created above after merging including the file content obtained using the $str variable so that everything can be stored into the database.

Coder
  • 6,381
  • 2
  • 9
  • 10
  • 2
    And what have you tried to debug this? It should be fairly easy to inspect what is sent to the webserver through your browser's developer tools – Nico Haase Apr 11 '18 at 16:34
  • Are there any errors in your PHP-logs? – Luca Kiebel Apr 11 '18 at 16:36
  • @NicoHaase Response header is blank as I mentioned in my post. I can see `accept.php` under network tab. What else I should be looking at? – Coder Apr 11 '18 at 16:39
  • try handling your error in the `.ajax` call as well. ie: `$.ajax({...error: function(xhr,status,error){...}...})` – Popmedic Apr 11 '18 at 16:39
  • You could check which elements are sent to the server in the developer console, and after all, you don't set any header in `accept.php`, so where should they come from? – Nico Haase Apr 11 '18 at 16:41
  • 1
    BTW you do see that displaying is not defined for: `var_dump($displaying)` and you know you don't need to echo your html in send.php, just put the html outside the `` section... – Popmedic Apr 11 '18 at 16:42
  • @Popmedic I corrected the `var_dump($displaying);` to `var_dump($displayImg);`, also moved the HTML outside php tags. Also, I included ` alert("Returndata"+returndata);` inside success function and I could see `Returndata ` alert pop-up. Still I don't see any variables in developers tools. – Coder Apr 11 '18 at 16:53
  • what browser's developers tools? – Popmedic Apr 11 '18 at 16:57
  • @Popmedic chrome – Coder Apr 11 '18 at 17:01
  • this might help with understanding how to return those images... https://stackoverflow.com/questions/2633908/php-display-image-with-header ... you will have to set the content-type, content-length, ... – Popmedic Apr 11 '18 at 17:04
  • Thanks but I will be sending PDF and Docs eventually instead of Images. – Coder Apr 11 '18 at 19:55
  • I think it is that it is not responding at all, check the pup logs to see what the error is. – Popmedic Apr 11 '18 at 22:46

1 Answers1

0

Maybe set something in the header for you to see...

if (isset($_POST['id'])) {                      
    $id = $_POST['id'];
    header ("ID: $id");
    var_dump($id);
    echo $id;
}else {
    header ("ID-Present: Nope");
}


if (isset($_POST['username'])) {
    $username = $_POST['username'];
    header ("User-Name: $username");
    var_dump($username);
    echo $username;
}else {
    header ("User-Name-Present: Nope");
}


if (isset($_FILES['profileImg'])) {
    $profileImg = $_FILES['profileImg'];
    header ("Profile-Image-Present: Yep");
    var_dump($profileImg);
    echo $profileImg;
} else {
    header ("Profile-Image-Present: Nope");
}

if (isset($_FILES['displayImg'])) {
    $displayImg = $_FILES['displayImg'];
    header ("Display-Image-Present: Yep");
    var_dump($displayImg);
    echo $displayImg;
} else {
    header ("Display-Image-Present: Nope");
}

UPDATED TO SHOW HOW TO SET QUERY PARAM(S)

If you want the headers to be something other then "Nope," you need to send those values in your javascript AJAX request like so:

function submitFileTest() { 
    var formData = new FormData();
    formData.append('id', $('[name="id"]').val());
    formData.append('username', $('[name="username"]').val());
    // Attach file
    formData.append('profileImg', $('input[type=file]')[0].files[0]);
    formData.append('displayImg', $('input[type=file]')[1].files[0]); 
    console.log("Form Data Test");
    console.log(formData);

    $.ajax({
        url: 'accept.php',
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          //alert(returndata);
          console.log(returndata);
        }
      });
}

UPDATED TO USE get_file_post_data FROM OTHER SOLUTION

I believe if you change the other solutions get_file_post_data function (I had to remove some of the useless code from this function, it annoyed me too much) to:

function get_file_post_data() {
    $files = array();
    $post = $_POST;
    foreach ($_FILES as $key_a => $data_a) 
        foreach ($data_a as $key_b => $data_b) {
            // Add this --->
            if ($key_b == 'tmp_name')
                $files['data'][$key_a] = base64_encode(file_get_contents($data_b));
            // <--- end
            $files[$key_b][$key_a] = $data_b;
        }
    foreach ($files as $type => $data) merge_file_post_data($type, $data, $post);
    return $post;
}

Then when you convert into JSON with something like json_encode(get_file_post_data(), JSON_PRETTY_PRINT);, you will have JSON like so:

{
    "id": "123",
    "username": "kevin",
    "profileImg": {
        "name": "suggestions@1.png",
        "type": "image\/png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KTMInWQAAAe1JREFUOBGNlLtKXUEUhr3FGxowCnaCjVaiQghaW6SzsNDCNHkCfQcrJa1YaGNhL1j4AClTJCkkBDmCCEE0ihfQqHj5\/j3rD\/ucfY664JuZdZ01s+ecurqiNIapm3kFSnAJF7ALS9AGkqY01R5dbJyQa\/gGszAMI\/AZfsERDIDEOUnLjQ2x7mO+h4Wcr3K5huEcOsJRXxkg3Tttsd6OAB3pTfjkbw67pu+wGnrh6O5O93YGH2oFYtcGkkk4BhfLunQhtzxIwBXoniQ6eqXY9hOH8vsjoKygk2QUjzY8Mz9EbFbIce7QBXZwtIK+qMT3mrQ0OmcM9Q70lCSukTRGJ2+w\/hpWJzso381vjF\/C4Xt0XDY7uQftH8yFNx\/sTRfx6YNYz28UaWly8hSqinaFVwneUA9aH0aPX+KcpFWM+Z328c2EX++vJdbzzD9i7Q5DLVbXxaqo5r\/wFiS3acpG2fTTk+QbyAzV2nVBHes9bEIvyH4Io3ADrxYf4xMZZ1CCvZj1RP7AR5A4NmmMhZb\/e9JCb+0d6OemO+yEE1DXVeW5I7eTMQEqqF+FRI\/+APTF\/Uspe9DVChKbiRL0pyr0hHRvsukavEFZMew1j+wOhohZh1OQTVc0DXrUjmH5svhudenLoI701fULsY9lUZ4ALVRR18zk4X0AAAAASUVORK5CYII=",
        "tmp_name": "\/private\/var\/tmp\/phpBU7D0c",
        "error": 0,
        "size": 941
    },
    "displayImg": {
        "name": "suggestions@2.png",
        "type": "image\/png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM\/rhtAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAA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vZTuT9csLbJcWFxrdXZxMitEs0B4IPwRlE44uplqlqD32UW5\/S2Q4LospNIjJkLzFXkpDKPSv0S7YYIObKQ92680SPBn4eST2Cimnc2cg3KE0+\/lSpwO2hVkt6V7BKTKo8avPD4eSA5sFZAqfPlyzBfBJQHCzwWk2dbIRuuv9qeCPGLg4hsR8VjWK3l1Fd9WnGf9YXC4IimUrtDB4GGPb4xAj6XwNPTxDAc0SpITwovhmULuSe6MeDj2RLzHoltNOcHHFP6jwA3OJ1L5UDwh\/7GIPVGI9XjBVK3p5XwlbkKSLwdVqyq6Qu9H3J\/SfL4hreIyD11dndzQpMEDFRkSLtRaXV29oVM47HtaMXy2kfhkxLdUKeQQUDHP+KdgfCY0Y83ESTwdDpzgUpKaIKTeL1fjDv6QaJYg\/oxRLX7lIY7NeglX75EE19yFrxBkXqaabhMSZGtwuADi2KyXcK2SoPejl5wP2lbCG8j38ZK38p8y5sApxjYdNjnyrPCqwI91eKYvNduHivFVvlJAfstUnW+YO1Per\/z\/cksgoTLgcJnD+1mmmRUvK28FqgPuCvcCfJoVgX1C4LvS\/82YQ6b2UmUmPp0LRc9BYQ9SSfYX71jaaIQ2CflwUEGPqdlequxBbsqNuDGnc6lAsosEXmlFYOfNMSL0C6WSk39+uminiKvHT8WvhbUC+5HqsbQsN6eWg\/OXcD36vIcRx2e9hCsBVYXK8Y4mMaoKF1XFRmVZfr4leUiPC\/zDVVrKJugK8INnQHhOYJuQzKPRZvm9D0mehL8Q3hEcr2aaVNmDMHMyjwskMCZ4WVluwKHwA13NXEi8lJStoMldiT4ZegUeJ1SK6hkkw8HhZ8Jg2EsfEsVVElf+E0WTSCu8Hnco9fyrlFUhqFj5Y4UEWVZOtBPeFzFU9X+XYpIf6e7DAvuPE\/ul8JZgKfralqT\/BVPW\/p9Rsv1pAAAAAElFTkSuQmCC",
        "tmp_name": "\/private\/var\/tmp\/php3kezNJ",
        "error": 0,
        "size": 1635
    }
}

If you would like to cut the response time in about half, you can try doing some poorman's threading in PHP...

Popmedic
  • 1,791
  • 1
  • 16
  • 21