Last active
February 27, 2024 19:57
-
-
Save mohsinrasool/50e0f43af626867dd05c to your computer and use it in GitHub Desktop.
Post multi-dimensional array using PHP Curl.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Post multi-dimensional array to a URL using PHP Curl. | |
* Usage: | |
* $req = new MultiDimArrayPost(); | |
* $req->postToURL('http://xyz.com/post',$_POST); | |
* | |
* @package default | |
* @author Mohsin Rasool | |
* | |
**/ | |
class MultiDimArrayPost { | |
/** | |
* It posts the provided $data to $url as it was posted from an HTML form | |
* | |
* @return void | |
* @author Mohsin Rasool | |
* | |
**/ | |
public function postToURL($url, $data= $_POST) | |
{ | |
$post = array(); | |
$this->http_build_query_for_curl($data, $post); | |
$post['pardot'] =true; | |
//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($post)); | |
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($post)); | |
//execute post | |
$result = curl_exec($ch); | |
//close connection | |
curl_close($ch); | |
} | |
/** | |
* It recursively converts the multi dimension (deep) array to single dimension array as it was posted from an html form | |
* | |
* @return void | |
* @author Mohsin Rasool | |
* | |
**/ | |
private function http_build_query_for_curl( $arrays, &$new = array(), $prefix = null ) { | |
if ( is_object( $arrays ) ) { | |
$arrays = get_object_vars( $arrays ); | |
} | |
foreach ( $arrays AS $key => $value ) { | |
$k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key; | |
if ( is_array( $value ) OR is_object( $value ) ) { | |
$this->http_build_query_for_curl( $value, $new, $k ); | |
} else { | |
$new[$k] = $value; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment