From dc9bb513eca41b004233bd07eda35820bb76d6ba Mon Sep 17 00:00:00 2001 From: php-curl-class Date: Sat, 24 Aug 2013 13:04:02 -0700 Subject: [PATCH] Use http_build_multi_query() to build POST data string containing multiple values for the same key --- Curl.class.php | 27 ++++++++++++++++++++++++++- tests/run.php | 2 +- tests/server.php | 3 ++- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/Curl.class.php b/Curl.class.php index ca49f9f..a2bb1fc 100644 --- a/Curl.class.php +++ b/Curl.class.php @@ -23,7 +23,7 @@ class Curl { function post($url, $data=array()) { $this->setopt(CURLOPT_URL, $url); $this->setopt(CURLOPT_POST, TRUE); - $this->setopt(CURLOPT_POSTFIELDS, $data); + $this->setopt(CURLOPT_POSTFIELDS, $this->_postfields($data)); $this->_exec(); } @@ -81,6 +81,31 @@ class Curl { curl_close($this->curl); } + function http_build_multi_query($data, $key=NULL) { + $query = array(); + + foreach ($data as $k => $value) { + if (is_string($value)) { + $query[] = urlencode(is_null($key) ? $k : $key) . '=' . urlencode($value); + } + else if (is_array($value)) { + $query[] = $this->http_build_multi_query($value, $k . '[]'); + } + } + + return implode('&', $query); + } + + function _postfields($data) { + $multidimensional = !(count($data) === count($data, COUNT_RECURSIVE)); + + if ($multidimensional) { + $data = $this->http_build_multi_query($data); + } + + return $data; + } + function _exec() { $this->response = curl_exec($this->curl); $this->curl_error_code = curl_errno($this->curl); diff --git a/tests/run.php b/tests/run.php index 9ec5003..448cc49 100644 --- a/tests/run.php +++ b/tests/run.php @@ -53,7 +53,7 @@ class CurlTest extends PHPUnit_Framework_TestCase { 'wubble', 'wobble', ), - )) === '{"test":"post_multidimensional","key":"file","file":["wibble","wubble","wobble"]}'); + )) === 'test=post_multidimensional&key=file&file%5B%5D=wibble&file%5B%5D=wubble&file%5B%5D=wobble'); } public function testPostFilePathUpload() { diff --git a/tests/server.php b/tests/server.php index bad33a8..4a24cbc 100644 --- a/tests/server.php +++ b/tests/server.php @@ -20,7 +20,8 @@ if ($test == 'http_basic_auth') { exit; } else if ($test === 'post_multidimensional') { - echo json_encode($_POST); + $http_raw_post_data = file_get_contents('php://input'); + echo $http_raw_post_data; exit; } else if ($test === 'post_file_path_upload') {