Search code examples
phpcurlinternal-server-error

curl_setopt Internal Server Error if I pass an array


I'm trying to call a web service and it was working when passing a json object to curl_setopt($cSession, CURLOPT_POSTFIELDS, $patientJS) but the object sent didnt have the right structure son I pass now an array and I get an internal server error. If I print curl_error() it tells me

Warning: curl_error(): 1044 is not a valid cURL handle resource

    $patient = array('nom' => $_POST['nom'], 
    'prenom' => $_POST['prenom'], 
    'login' => $_POST['email'], 
    'password' => $_POST['password'],
    'datenaissance' => $_POST['datenaissance'],
    'sexe' => $_POST['sexe']);


$patientJS = json_encode($patient);

$cSession = curl_init();

curl_setopt($cSession, CURLOPT_URL, 'http://medicitussrv.herokuapp.com/enrollPatient');
curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cSession, CURLOPT_POST, 1);
curl_setopt($cSession, CURLOPT_POSTFIELDS, $patientJS);

$result = curl_exec($cSession);

curl_close($cSession);

This works but sends an object like

{ '{"nom":"Preciado","prenom":"Rodriguez","login":"[email protected]","password":"Medicitus1","datenaissance":"2017-09-06","sexe":"homme"}': '' }

pass an array:

    $patient = array('nom' => $_POST['nom'], 
    'prenom' => $_POST['prenom'], 
    'login' => $_POST['email'], 
    'password' => $_POST['password'],
    'datenaissance' => $_POST['datenaissance'],
    'sexe' => $_POST['sexe']);


$cSession = curl_init();

curl_setopt($cSession, CURLOPT_URL, 'http://medicitussrv.herokuapp.com/enrollPatient');
curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cSession, CURLOPT_POST, 1);
curl_setopt($cSession, CURLOPT_POSTFIELDS, $patient);

$result = curl_exec($cSession);

curl_close($cSession);

This returns an Internal Server Error


Solution

  • Use http_build_query when you send array in curl it will create url encoded string

        $patient = array('nom' => $_POST['nom'], 
        'prenom' => $_POST['prenom'], 
        'login' => $_POST['email'], 
        'password' => $_POST['password'],
        'datenaissance' => $_POST['datenaissance'],
        'sexe' => $_POST['sexe']);
    
    
    $cSession = curl_init();
    
    curl_setopt($cSession, CURLOPT_URL, 'http://medicitussrv.herokuapp.com/enrollPatient');
    curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($cSession, CURLOPT_POST, 1);
    curl_setopt($cSession, CURLOPT_POSTFIELDS, http_build_query($patient));