Sending variable instead of POSTFIELD in curl

I have the following code which works fine for sending the ($_POST["myData"]

if (isset($_POST["myData"])) 
				{ 
		    		$curl = curl_init();
       				  curl_setopt_array($curl, array(
					  CURLOPT_PORT => "9090",
					  CURLOPT_URL => "http://localhost:9090/mywebservice/insertDataToDB",
					  CURLOPT_RETURNTRANSFER => true,
					  CURLOPT_ENCODING => "",
					  CURLOPT_MAXREDIRS => 10,
					  CURLOPT_TIMEOUT => 30,
					  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					  CURLOPT_CUSTOMREQUEST => "POST",
					  CURLOPT_POSTFIELDS => $_POST["myData"],
					 CURLOPT_HTTPHEADER => array(
						"Cache-Control: no-cache",
						"Content-Type: application/json"
					
						),
					  ));

					$response_post_march22 = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
					  echo "cURL Error #:" . $err;
					} else {
					  echo $response_post_march22;
					} 
					
				}

However, when I try to send an associative array variable like this, it doesn’t work :

if (isset($arr)) 
				{ 
		    		$curl = curl_init();
       				  curl_setopt_array($curl, array(
					  CURLOPT_PORT => "9090",
					  CURLOPT_URL => "http://localhost:9090/mywebservice/insertDataToDB",
					  CURLOPT_RETURNTRANSFER => true,
					  CURLOPT_ENCODING => "",
					  CURLOPT_MAXREDIRS => 10,
					  CURLOPT_TIMEOUT => 30,
					  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					  CURLOPT_CUSTOMREQUEST => "POST",
					  //CURLOPT_POSTFIELDS => $_POST["myData"],
					  CURLOPT_POSTFIELDS => $arr,
					  
					  CURLOPT_HTTPHEADER => array(
						"Cache-Control: no-cache",
						"Content-Type: application/json"
					
						),
					  ));

					$response_post_march22 = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
					  echo "cURL Error #:" . $err;
					} else {
					  echo $response_post_march22;
					} 
					
				}

Try setting the following and the returned warnings and errors should give detailed information rather than “it doesn’t work”.

ini_set('display_errors, 'true');
error_reporting(-1); // maximum errors and warnings

Also for the script that works try using var_dump($variableThatWorks); and compare with var_dump($variableThatDoesNotWork);

Also check the following page:

https://curl.haxx.se/libcurl/c/CURLOPT_POSTFIELDS.html

Thanks. I forgot to json_encode($arr) and send it. I was simply sending it as $arr which was the problem.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.