Avatar of vikasbapat
vikasbapat
 asked on

Curl Bad Request

We are getting error while using adding curl request in loop as shown in below code.
eventhough first entry from the loop gets consumed properly , from 2nd loop onwards we get error..

#$data is large XML file, which we divide in chunks and pass in for loop where curl request is added.

$posting1 = "xmldata=" . rawurlencode($data);
$Medi_URL2 = "https://proda.mediemr.net:4443/pls/htmldb/MEDIDATA.GET_SURESCRIPT_DATA_NEW";
$i = 0;
$len = 32000;
$arr2 = array();

while($i < strlen($posting1)) {
    $arr2[] = substr($posting1, $i, $len);
    $i += $len;
}


for($cnt=0;$cnt<count($arr2);$cnt++)
{
      $value=      $arr2[$cnt];
        $ch = curl_init();
      
      curl_setopt($ch, CURLOPT_URL,$Medi_URL2);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS,$value);
   

 ### Return post result string, no just success code
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


  $result = curl_exec ($ch);
  curl_close ($ch);
   unset($ch);
  unset($value);
}
BadRequestError.jpg
PHPApache Web ServerWeb Development

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
F P

Try a foreach loop instead of a for loop which counts an array. It's faster and more flexible. Lemme know if this works for you:

foreach($arr2 as $value)
{
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL,$Medi_URL2);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS,$value);

 ### Return post result string, no just success code
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec ($ch);
    curl_close ($ch);
}

unset($value);

Open in new window

ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy