Charles_R Charles_R - 4 months ago 19
PHP Question

curl post form data is not working

I want to post form data to a service but it shows some error with form parameters, this is my curl script sample:

// header('Content-Type:application/json');

$data = array();
$data = json_decode(file_get_contents('php://input'), true);

$user= $data["username"];
$pass= $data["password"];

$form_data = array('username' => $user, 'password' => $pass);
$url = "http://localhost:8585/auth/session";

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 75);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);

$result = curl_exec($ch);

echo "result $result";

on the service site it produce a error like this:

@FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded


replace this line

curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);

with this line

curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($form_data));

the reason you got an error is you are sending an array, but what you need to send is a urlencoded string. refer this: