PHP Use CURL to post an array to URL

Can someone give me an example on how to take a multi-dimensional array ($params) and post that array to a URL. I then need to be able to use 'extract' on the array to create variables on the remote end.
ITNCAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Please post the $params array so we can see exactly what the data looks like.  Sending a multidimensional array is a very, very rare occurrence.  More likely you will want to take a mainstream approach, such as sending a JSON string.
0
J NUnicorn wranglerCommented:
Here is a working curl function which you can use to cURL to GET POST or DELETE

function CURL($url, $json, $action){
		try{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
			curl_setopt($ch, CURLOPT_URL, $url);
		   
		   //
			switch($action){
					case "POST":
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
					curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
					break;
			 
				case "GET":
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
					break;
			 
				case "DELETE":
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
					curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
			 
				default:
					break;
			}
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 10);
			$output = curl_exec($ch);
			
			//END CURL
			curl_close($ch);
			
			//RETURN DATA
			return $output;
		
		}catch(Excetion $e){
				//THE CURL WAS UNSUCCESSFUL	
				echo '<div>Unable to get data!</div>';
				
				//RETURN FALSE
				return false;
		}
	}

Open in new window

0
duncanb7Commented:
Take a look this example link for curl  post
http://davidwalsh.name/curl-post

And php.net also provide the manual for curl
http://php.net/manual/en/function.curl-setopt.php

Duncan
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

ITNCAuthor Commented:
Here is an example of the $params array:

Array
(
    [accountid] => 5
    [serviceid] => 5
    [userid] => 1
    [domain] => 
    [username] => test
    [password] => test
    [packageid] => 9
    [pid] => 9
    [serverid] => 4
    [type] => other
    [producttype] => other
    [moduletype] => test
    [configoption1] => TEST123
    [configoption2] => 
    [configoption3] => 
    [configoption4] => 
    [configoption5] => 
    [configoption6] => 
    [configoption7] => 
    [configoption8] => 
    [configoption9] => 
    [configoption10] => 
    [configoption11] => 
    [configoption12] => 
    [configoption13] => 
    [configoption14] => 
    [configoption15] => 
    [configoption16] => 
    [configoption17] => 
    [configoption18] => 
    [configoption19] => 
    [configoption20] => 
    [configoption21] => 
    [configoption22] => 
    [configoption23] => 
    [configoption24] => 
    [customfields] => Array
        (
            [*Note] => 
        )

    [configoptions] => Array
        (
            [MSRP] => MSRP
            [Wan Failover] => OFF
            [Passthru] => OFF
            [DHCP] => ON
            [DNS] => ON
            [NAT] => ON
        )

    [clientsdetails] => Array
        (
            [userid] => 1
            [id] => 1
            [firstname] => test
            [lastname] => test
            [fullname] => test test
            [companyname] => test
            [email] => test@test.com
            [address1] => 23605 test Rd
            [address2] => 23605 test Rd
            [city] => test
            [fullstate] => test
            [state] => te
            [postcode] => 11111
            [countrycode] => US
            [country] => US
            [statecode] => te
            [countryname] => United States
            [phonecc] => 1
            [phonenumber] => 111-111-1111
            [phonenumberformatted] => +1.1111111111
            [billingcid] => 0
            [notes] => 
            [password] => test
            [twofaenabled] => 
            [currency] => 1
            [defaultgateway] => 
            [cctype] => 
            [cclastfour] => 
            [securityqid] => 0
            [securityqans] => 
            [groupid] => 0
            [status] => Active
            [credit] => 924.00
            [taxexempt] => 
            [latefeeoveride] => 
            [overideduenotices] => 
            [separateinvoices] => 
            [disableautocc] => 
            [emailoptout] => 0
            [overrideautoclose] => 0
            [language] => 
       
        )

    [server] => 1
    [serverip] => 
    [serverhostname] => test.test.net
    [serverusername] => 
    [serverpassword] => 
    [serveraccesshash] => testhash
    [serversecure] => 
    [action] => create
)

Open in new window

0
J NUnicorn wranglerCommented:
Hi,

can you not json_econde the array and then use it in my function above?

ex:
 $json=json_encode($params);
$url='www.somewhere.com';
$data=CURL($url, $json, 'POST')

echo '<pre>';
print_r($data);
echo'</pre>';

Open in new window

0
ITNCAuthor Commented:
I will try that and get back with you
0
ITNCAuthor Commented:
M. Jayme Nagy,

Should I be able to grab the posted data on the remote end using $_POST['data'] ?
0
Ray PaseurCommented:
Your choice of GET or POST will depend on whether the request can change the state of the server.  If the request is idempotent, you can use GET.  If the request is not idempotent you must use POST.  If you're not sure what idempotent means, use POST (but look it up, because it's an important concept in computer science).

It's not clear to me what the data elements in the $_GET or $_POST array will look like.  On the target server, you will want to use a combination of output buffering and var_dump() to capture the request data.  Then you can use error_log or similar to put the request data into a place where it will be visible.  You might email it to yourself.  The reason you have to jump through some extra hoops is because the cURL request is made "server-to-server" and there is no browser output along the way.

The lack of browser output means that it's somewhat difficult to debug communication errors.  Only the sending server (which is acting as a client) will be able to talk to you about any problems.  You might want to be familiar with curl errors and you might want to use a script that will visualize these in case any of them occur.
http://curl.haxx.se/libcurl/c/libcurl-errors.html
0
J NUnicorn wranglerCommented:
echo '<pre>';
print_r($data);
echo'</pre>';

will return the result (changes for POST DELETE or GET) from the receiving server. the receiving server should know how to interpret the data. Its difficult to guide you without adequate information and @ray is one of the forums best
0
ITNCAuthor Commented:
So right now on the remote end I have the following:

$vars = print_r($_POST);
echo "POST: " . $vars . "";

And the result I get is:
POST: 1

Any reason why it is returning a 1?
0
J NUnicorn wranglerCommented:
try

echo '<pre>';
 print_r($_REQUEST);
echo '</pre>';
0
ITNCAuthor Commented:
That also prints a 1
0
Ray PaseurCommented:
All of the PHP functions are documented on the PHP.net web site. If you're not sure why a function is doing something (like returning "1") you can look it up by going to http://php.net and typing the function name into the search box at the upper right.  Example here: http://php.net/manual/en/function.print-r.php
0
J NUnicorn wranglerCommented:
what are you trying to get?
0
J NUnicorn wranglerCommented:
0
Ray PaseurCommented:
Put the URL of your web service at line 159 and try this for starters.  It should at least get you a script that will parse and a cURL call that will show you the cURL errors, if any.

<?php // demo/temp_itnc_local.php
error_reporting(E_ALL);
echo '<pre>';

/**
 * SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28476467.html#a40197729
Array
(
    [accountid] => 5
    [serviceid] => 5
    [userid] => 1
    [domain] =>
    [username] => test
    [password] => test
    [packageid] => 9
    [pid] => 9
    [serverid] => 4
    [type] => other
    [producttype] => other
    [moduletype] => test
    [configoption1] => TEST123
    [configoption2] =>
    [configoption3] =>
    [configoption4] =>
    [configoption5] =>
    [configoption6] =>
    [configoption7] =>
    [configoption8] =>
    [configoption9] =>
    [configoption10] =>
    [configoption11] =>
    [configoption12] =>
    [configoption13] =>
    [configoption14] =>
    [configoption15] =>
    [configoption16] =>
    [configoption17] =>
    [configoption18] =>
    [configoption19] =>
    [configoption20] =>
    [configoption21] =>
    [configoption22] =>
    [configoption23] =>
    [configoption24] =>
    [customfields] => Array
        (
            [*Note] =>
        )

    [configoptions] => Array
        (
            [MSRP] => MSRP
            [Wan Failover] => OFF
            [Passthru] => OFF
            [DHCP] => ON
            [DNS] => ON
            [NAT] => ON
        )

    [clientsdetails] => Array
        (
            [userid] => 1
            [id] => 1
            [firstname] => test
            [lastname] => test
            [fullname] => test test
            [companyname] => test
            [email] => test@test.com
            [address1] => 23605 test Rd
            [address2] => 23605 test Rd
            [city] => test
            [fullstate] => test
            [state] => te
            [postcode] => 11111
            [countrycode] => US
            [country] => US
            [statecode] => te
            [countryname] => United States
            [phonecc] => 1
            [phonenumber] => 111-111-1111
            [phonenumberformatted] => +1.1111111111
            [billingcid] => 0
            [notes] =>
            [password] => test
            [twofaenabled] =>
            [currency] => 1
            [defaultgateway] =>
            [cctype] =>
            [cclastfour] =>
            [securityqid] => 0
            [securityqans] =>
            [groupid] => 0
            [status] => Active
            [credit] => 924.00
            [taxexempt] =>
            [latefeeoveride] =>
            [overideduenotices] =>
            [separateinvoices] =>
            [disableautocc] =>
            [emailoptout] => 0
            [overrideautoclose] => 0
            [language] =>

        )

    [server] => 1
    [serverip] =>
    [serverhostname] => test.test.net
    [serverusername] =>
    [serverpassword] =>
    [serveraccesshash] => testhash
    [serversecure] =>
    [action] => create
)
*/

// SIMULATE SOME PARTS OF THE ARRAY
$arr = Array
( 'accountid' => '5'
, 'serviceid' => '5'
, 'userid' => '1'
, 'domain' => ''
, 'username' => 'test'
, 'customfields' => Array
  ( '*Note' => ''
  )
, 'configoptions' => Array
  ( 'MSRP' => 'MSRP'
  , 'Wan Failover' => 'OFF'
  )
, 'clientsdetails' => Array
  ( 'userid' => '1'
  , 'id' => '1'
  , 'firstname' => 'test'
  , 'groupid' => '0'
  , 'status' => 'Active'
  , 'credit' => '924.00'
  , 'taxexempt' => ''
  , 'overrideautoclose' => '0'
  , 'language' => ''
  )
, 'server' => '1'
, 'serverip' => ''
, 'serverhostname' => 'test.test.net'
, 'action' => 'create'
)
;

// SHOW THE ARRAY WE ARE USING
var_dump($arr);

// MAKE A JSON STRING
$jso = json_encode($arr);

// MAKE A REQUEST VARIABLE THAT INCORPORATES THE JSON STRING
$req = array('data' => $jso);

// IDENTIFY THE URL OF THE WEB SERVICE
$url = '';

// CALL THE REMOTE SERVER AND SHOW THE RESPONSE
$response = my_curl($url, $req);
var_dump($response);


// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function my_curl
( $url
, $get_array=array()
, $timeout=3
, $error_report=TRUE
)
{
    // PREPARE THE ARGUMENT STRING IF NEEDED
    $get_string = NULL;
    foreach ($get_array as $key => $val)
    {
        $get_string
        = $get_string
        . $key
        . '='
        . urlencode($val)
        . '&'
        ;
    }
    $get_string = rtrim($get_string, '&');
    if (!empty($get_string)) $url .= '?' . $get_string;

    // START CURL
    $curl = curl_init();

    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE THIS BLANK

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt( $curl, CURLOPT_URL,            $url  );
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0'  );
    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header  );
    curl_setopt( $curl, CURLOPT_REFERER,        'http://www.google.com'  );
    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate'  );
    curl_setopt( $curl, CURLOPT_AUTOREFERER,    TRUE  );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE  );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE  );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );
    curl_setopt( $curl, CURLOPT_FAILONERROR,    TRUE  );

    // THIS SEEMS TO LET IT WORK WITH HTTPS SITES
    curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);

    // ON FAILURE HANDLE CREATION OF ERROR MESSAGE
    if ($htm === FALSE)
    {
        if ($error_report)
        {
            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS RETURN XML / HTML STRING
    curl_close($curl);
    return $htm;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ITNCAuthor Commented:
Ray,

I was able to get the array I needed using your script above. Thank you all for your expertise and quick responses. I have much to learn but this helps tremendously.
0
Ray PaseurCommented:
Great!  Thanks for using E-E, it can be a great learning community.  All the best, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.