[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PHP Use CURL to post an array to URL

Posted on 2014-07-15
19
Medium Priority
?
993 Views
Last Modified: 2014-07-16
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.
0
Comment
Question by:ITNC
  • 6
  • 6
  • 5
  • +1
19 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40197708
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
 
LVL 6

Expert Comment

by:J N
ID: 40197718
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
 
LVL 13

Expert Comment

by:duncanb7
ID: 40197721
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:ITNC
ID: 40197729
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
 
LVL 6

Expert Comment

by:J N
ID: 40197752
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
 

Author Comment

by:ITNC
ID: 40197758
I will try that and get back with you
0
 

Author Comment

by:ITNC
ID: 40197817
M. Jayme Nagy,

Should I be able to grab the posted data on the remote end using $_POST['data'] ?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40197858
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
 
LVL 6

Expert Comment

by:J N
ID: 40197883
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
 

Author Comment

by:ITNC
ID: 40197914
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
 
LVL 6

Expert Comment

by:J N
ID: 40197922
try

echo '<pre>';
 print_r($_REQUEST);
echo '</pre>';
0
 

Author Comment

by:ITNC
ID: 40197930
That also prints a 1
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40197934
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
 
LVL 6

Expert Comment

by:J N
ID: 40197936
what are you trying to get?
0
 
LVL 6

Expert Comment

by:J N
ID: 40197955
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 40198290
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
 

Author Comment

by:ITNC
ID: 40199133
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40199164
Great!  Thanks for using E-E, it can be a great learning community.  All the best, ~Ray
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month20 days, 9 hours left to enroll

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question