In my application, on a particular page the user can upload an image and fill in several fields. I send that data to the web server (php) using an AJAX POST. The data is set using FormData like so:
var formData = new FormData();
formData.append('image', this.imageUploadField.files[0]);
formData.append('levelName', this.nameField.value);
formData.append('cost', this.monthlyCostField.value);
xhttp.open("POST", "http://example.com");
xhttp.setRequestHeader("Content-Type", "multipart/form-data");
xhttp.send(formData);
I retrieve the temp image server side with $_FILES. I then need to push that image and data to a REST API for processing, however I'm having trouble doing so. Here's how I am sending the image via the web server. The first problem is it's arriving to the API and only retrievable via the $_POST global, with no file name, path, etc... which I don't understand.
$data = file_get_contents('php://input');
// Setup http request
$options = ["http" =>
["method" => "POST",
"header" => "Content-Type: multipart/form-data",
"content" => $data,
"header" => "Authorization: " . $_SESSION['token'] ] ];
// Call API
$apiResponse = file_get_contents($apiUrl, NULL, stream_context_create($options));
How do I go about sending both the image and data to the API server. Please note I am not using curl. Also should note that both the webserver and api are running on my localhost at the moment.
UPDATE: To add more detail. After implementing multipart/form-data, this is what it looks like when I print_r($_POST);
:
------WebKitFormBoundaryI96wB7anw56O2g4M Content-Disposition: form-data; name="image"; filename="blue_tier.png" Content-Type: image/png
Binary Data
------WebKitFormBoundaryI96wB7anw56O2g4M Content-Disposition: form-data; name="levelName"
Test Name ------WebKitFormBoundaryI96wB7anw56O2g4M Content-Disposition: form-data; name="cost"
4.99
I can't seem to get to the data. $_POST['levelName'] for example is null.