im having some trouble with curl. I have an foreachloop where i make an simple postrequest with curl at the end. But i always get an 403 back.
But when i try the same code with an defined array and without a foreach its working.
I hope someone has an idea for that.
Test Array
$test = array (
'name' => 'Peter Apimann',
'email' => '[email protected]',
'website' => 'www.a.de',
'phonenumber' => '123456789',
'company' => 'Apimann Gmbh',
'address' => 'Straße 1',
'city' => 'Neu-Isengard',
'zip' => '12345',
'state' => 'Mordor',
'description' => 'We are a fictional Company',
'isCompetitor' => false,
'source' => '11',
'status' => '16',
'custom_fields[leads][11]' => "<a target='_blank' href='https://google.de'>visit link</a>"
);
//var_dump($test);
$url = "https://example.com/api/endpoint";
$requestHeader[] = "authtoken: 123456789";
$fields_string = http_build_query($test);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$requestHeader);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
In my foreach Loop
<?php
foreach( $postdata AS $item ) {
...
$url = "https://example.com/api/endpoint";
$requestHeader[] = "authtoken: 123456789";
$fields_string = http_build_query($item);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$requestHeader);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}
CodePudding user response:
Okay, i got it. i´m sure it´s not the best solution but it works. :)
First i put each item into an own array instead of do the post directly.
foreach( $postdata AS $item ) {
...
$itemsToSend[] = $item;
}
Then i created a simple function
function postTheItems ($postarray) {
$url = "https://example.com/api/endpoint";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$requestHeader= array(
"authtoken: 123456789",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeader);
$postarray= http_build_query($postarray);
$data = <<<DATA
$postarray
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
Finally i created another foreach and call the function
foreach ( $final_post_data AS $item ) {
postTheItems ($itemsToSend);
}