Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include array data in CURLOPT_POSTFIELDS? [duplicate]

Tags:

I'm basically processing a HTML form with PHP and then sending it off elsewhere for storage and processing. However I'm having trouble sending array lists through curl. I need to do it in such a way that when it gets to the receiving server it's as if it has come straight from the input form.

I don't receive any errors when using the function if I serialize the arrays, however this makes them unreadable by the server, so they need to keep the post format as if they were coming from a HTML form.

I'm using Kohana but principles of Curl are still the same, here's my code:

            $path = "/some/process/path";             $store = "http://www.website.com";              $url = $store . $path;              $screenshots = array();             $screenshots[0] = 'image1.jpg';             $screenshots[1] = 'image2.jpg';             $screenshots[2] = 'image3.jpg';              $videoLinks = array();             $videoLinks[0] = 'video1.wmv';             $videoLinks[1] = 'video2.wmv';              $params = array(                 'id' => '12',                 'field1' => 'field1text',                 'field2' => 'field2text',                 'field3' => 'field3text',                 'screenshots' => $screenshots,                 'videoLinks' => $videoLinks,             );              $options = array(                 CURLOPT_HTTPHEADER => array("Accept: application/json"),                 CURLOPT_TIMEOUT => 30,                 CURLOPT_POST => TRUE,                 CURLOPT_POSTFIELDS => $params,             );              $data = Remote::get($url, $options);             $json = json_decode($data); 

Cheers.

like image 387
diggersworld Avatar asked Feb 24 '11 12:02

diggersworld


2 Answers

CURLOPT_POSTFIELDS => http_build_query($params), 

http://php.net/manual/en/function.http-build-query.php

like image 180
delphist Avatar answered Nov 06 '22 18:11

delphist


I just wanted to share an alternative to http_build_query()

You can include array inputs with CURLOPT_POSTFIELDS by supplying each subarray item separately.

Instead of...

$videoLinks = array(); $videoLinks[0] = 'video1.wmv'; $videoLinks[1] = 'video2.wmv';  $params = array(     ...     'videoLinks' => $videoLinks;     ... ); 

... do this ...

$params = array(     ...     'videoLinks[0]' => 'video1.wmv';     'videoLinks[1]' => 'video2.wmv';     ... ); 
like image 36
klkl Avatar answered Nov 06 '22 18:11

klkl