web-dev-qa-db-fra.com

Comment utiliser les tableaux dans les requêtes cURL POST

Je me demande comment puis-je faire ce tableau de support de code? Pour le moment, le tableau images ne semble envoyer que la première valeur.

Voici mon code:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images[]' => urlencode(base64_encode('image1')),
            'images[]' => urlencode(base64_encode('image2'))
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

et c'est ce qui est reçu à l'api

VAR: username = annonymous
VAR: api_key = 1234
VAR: images = Array
array(3) { 
         ["username"]=> string(10) "annonymous" 
         ["api_key"]=> string(4) "1234" 
         ["images"]=> array(1) { // this should contain 2 strings :( what is happening?
                               [0]=> string(8) "aW1hZ2Uy" 
                               } 
         }

Qu'arrive-t-il à la deuxième valeur de images[]?

30
Mr. King

Vous créez simplement votre tableau de manière incorrecte. Vous pouvez utiliser http_build_query :

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

Ainsi, le code entier que vous pourriez utiliser serait:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>
71
Benjamin Powers