I am submitting the data from a from via Ajax and it needs to make a curl request to an endpoint. I am not getting any errors but when I check the data in the endpoint it isn't there. If I submit the form just using normal html then it works. So, something is incorrect with my CURL code I would imagine.
<?php
$response = [];
$message = '';
$data = [
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
];
$options = [
CURLOPT_URL => 'https://someEndpoint.com?encoding=UTF-8',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => 1
];
$curl = curl_init();
curl_setopt_array($curl, $options);
$results = curl_exec($curl);
curl_close($curl);
$response['success'] = true;
$response['message'] = 'Thank you, your request has been submitted.';
echo json_encode($response);
You're currently passing the post fields as an array. However, cURL expects it to be passed as a string in this format:
first_name=foo&last_name=bar&...
It's just like a query string.
We can use http_build_query() to convert the array to the above format:
CURLOPT_POSTFIELDS => http_build_query($data),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.