Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

494
Views
Send Image and Data from PHP to API

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.

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!