send form with files to REST API with curl php

0

I am trying to send a form with files to a REST API in curl with the version php 5.6, but when uploading the file it sends me a message saying that some fields have not been received and I have already tried everything what comes to mind (also with CurlFile) and nothing. If someone would be so kind to guide me I would be very grateful, greetings! annex the code.

    /*
        se extrae el token
    */
    $token = auth();

    /*
        se establecen los tipos MIME en la cabecera
    */
    header('content-type: application/json');
    header('content-lenght: 169');
    header('x-gatekeeper-sessiontoken: '.$token);   

    /*
        se crea un objeto curl
        posteriormente se crea un file_curl
        y por ultimo se crea un array con el id del lookuplist y el filecurl
    */
    $handle = curl_init('https://www.url_de_la_api.com/api/lookuplist/?token='.$token);
    $newData = array('id' => trim($data['ID']),'listname' => trim($data['LISTNAME'],'file' => '@'.realpath($data['FILE']).";filename=Contacts.csv");

    print_r($newData);

    /*
        se establecen las opciones del objeto curl
    */
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_UPLOAD, 1);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $newData);

    /*
        se ejecuta el objeto curl y se guarda la respuesta
        asi mismo tambien se capturan los errores en la ejecucion de curl en dado caso que existiesen
        y se guarda la respuesta
    */
    $response   = curl_exec($handle);
    $errors     = curl_error($handle);

    /*
        se extrae el JSON de la respuesta de la ejecucion del objeto curl
    */
    $responseJSON = json_decode($response);

    /*
        se cierra el objeto curl
    */
    curl_close($handle);

    /*
        se crea una condicional para ver si el objeto curl se ejecuto correctamente
    */
    if (!$errors) {
        header('content-type: application/json');
        echo "It's work!";
        print_r($response);
        unset($token,$handle,$file,$newData,$response,$errors,$responseJSON);

    }else{
        header('content-type: application/json');
        echo "Not work! :(";
        echo $errors;
        echo $responseJSON;
        unset($token,$handle,$file,$newData,$response,$errors,$responseJSON);
    }
    
asked by Jesus Solis 18.09.2017 в 15:32
source

1 answer

-1

Resolved by setting CURLOPT_SAFE_UPLOAD to false

With which the options of curl would be as follows:

/*
    se establecen las opciones del objeto curl
*/
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_UPLOAD, 1);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $newData);
/* Se agrega esta línea */
curl_setopt($handle, CURLOPT_SAFE_UPLOAD, false);
    
answered by 18.09.2017 / 18:51
source