Link to home
Start Free TrialLog in
Avatar of ToddBPeterson
ToddBPeterson

asked on

Getting Values From CURLOPT_POSTFIELDS

I am trying to figure out how to grab the POST data, from a PHP page that was invoked with a CURL method, having an array passed via the CURLOPT_POSTFIELDS.

Since you don't provide a name for the POST field, how do you go about getting and parsing the value on the receiving PHP side?

Here's an example:

CallingPage.php

<?
     $json_url = 'http://someURL/ReceivingPage.php';
     $json_string = '{
          "Key1":"Value1",
          "Key2":"Value2",
          "Key3":"Value3"
     }';

     $ch = curl_init();  

     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
     curl_setopt($ch, CURLOPT_URL, $json_url);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);

     $response = curl_exec($ch);
?>

ReceivingPage.php

<?
     // This is the receiving page...
     // How do I get the array that was POSTed from the calling page?
     // there is no $_POST["name???"] to grab???
?>
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

I'm pretty sure you have to give it a name and urlencode the data part.  You also need to set...

curl_setopt($ch, CURLOPT_POST, 1);

for it to POST.

http://www.php.net/manual/en/function.curl-setopt.php
http://www.php.net/manual/en/function.json-decode.php
Avatar of ToddBPeterson
ToddBPeterson

ASKER

Thanks Dave!

How would you give the post parameter a name, in that usage context?  

From the PHP Manual:
This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

I tried something like:
$json_string = 'my_parm={
          "Key1":"Value1",
          "Key2":"Value2",
          "Key3":"Value3"
}';

Open in new window

Then tried, unsuccessfully to get:
$_POST["my_parm"]

Open in new window

I also set the option you recommended:
curl_setopt($ch, CURLOPT_POST, 1);

Open in new window

I appreciate your thoughts/input.

Best Regards,
Todd
Please see http://www.laprbass.com/RAY_temp_toddbpeterson.php

As a practical matter, you may need stripslashes() if your receiving script is running on a server that has magic quotes enabled.  Here is why you do not want magic quotes enabled.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_6630-Magic-Quotes-a-bad-idea-from-day-one.html

Unfortunately my server has magic quotes, so that is why you will see the backslashes in the output.  I think if you strip them you will find a workable JSON string.

<?php // RAY_temp_toddbpeterson.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);


// DEMONSTRATE HOW TO USE CURL POST TO START AN ASYNCHRONOUS PROCESS
// http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28084355.html

// TEST DATA FROM THE POST AT EE
$json_string = '{
          "Key1":"Value1",
          "Key2":"Value2",
          "Key3":"Value3"
     }';



function curl_post($url, $post_array=array(), $timeout=2, $error_report=FALSE)
{
    // PREPARE THE POST STRING
    $post_string = NULL;
    foreach ($post_array as $key => $val)
    {
        $post_string .= $key . '=' . urlencode($val) . '&';
    }
    $post_string = rtrim($post_string, '&');

    // PREPARE THE CURL CALL
    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_URL,            $url         );
    curl_setopt( $curl, CURLOPT_HEADER,         FALSE        );
    curl_setopt( $curl, CURLOPT_POST,           TRUE         );
    curl_setopt( $curl, CURLOPT_POSTFIELDS,     $post_string );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout     );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE         );

    // EXECUTE THE CURL CALL
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);

    // ON FAILURE
    if (!$htm)
    {
        // PROCESS ERRORS HERE
        if ($error_report)
        {
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            echo "<pre>\n";
            var_dump($inf);
            echo "</pre>\n";
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS
    curl_close($curl);
    return $htm;
}


// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
$args["my_stuff"]  = $json_string;

// ACTIVATE THIS TO SEE THE ARRAY OF ARGS
// var_dump($args);

// SET THE URL (THIS SCRIPT JUST SENDS BACK WHAT IT GOT)
$url = "http://LAPRBass.com/RAY_bounce_post.php";

// CALL CURL TO POST THE DATA
$htm = curl_post($url, $args, 3, TRUE);

// SHOW WHAT CAME BACK, IF ANYTHING
if ($htm)
{
    echo "<pre>";
    echo htmlentities($htm);
}
else
{
    echo "NO RESPONSE YET FROM $url -- MAYBE BECAUSE IT IS RUNNING ASYNCHRONOUSLY";
}

Open in new window

HTH, ~Ray
Hey...  Thanks Ray!

I think I'm close...  just missing something simple...

What does the code for your http://www.laprbass.com/RAY_temp_toddbpeterson.php page look like?

I have used your example to build the post array string, I'm just not sure how to extract it on the receiving side.

In this example, I own the client and the Rest server, and am trying to extract the posted JSON from the client, in my Rest server.  Here is a summary of my client code (copied/pasted/simplified the source, so there may be some syntax errors, but you'll get the point:
<?

	function curlInvoke($url, $parms) {
		$ch = curl_init();  

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $parms);

		// Getting results 
		$response = curl_exec($ch); // Getting jSON result string 
		if($response === false) 
			return 'Curl error: ' . curl_error($ch);
		
		$obj = json_decode($response);

		return $obj;
	}


	$json_url = 'http://myURL/RestPage.php';   
	$json_string = '{
		"Account_id":1234,
		"Account_Name":"Sample Account",
		"AccountGuid":"987654321",
		"ConfigData":"Key:Value",
		"CSV_Data":"FirstName,LastName,Title Ross,Little,SallysList Gordon,Rivera, Krisin,Meemken,SallysList Charlie,Pettygrove,SallysList Rosemary,Bundscho, fn,ln,",
		"Identifier":0001,
		"Schedule_ID":"ScheduleID01",
		"SettingsData":"Key:Value",
		"State":1,
	}';

	// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
	$args["my_stuff"]  = $json_string;

	// ACTIVATE THIS TO SEE THE ARRAY OF ARGS
	// echo "JSON String Array: ";
	// var_dump($args);		

	// PREPARE THE POST STRING
	$post_string = NULL;
	foreach ($args as $key => $val)
	{
		$post_string .= $key . '=' . urlencode($val) . '&';
	}
	$post_string = rtrim($post_string, '&');

	$obj = curlInvoke($json_url, $post_string);	
	
?>

Open in new window

So on the receiving side, how do I get the value that was posted?  I think seeing http://www.laprbass.com/RAY_temp_toddbpeterson.php code will tell me exactly what I need

Thanks so much!
Todd
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Outstanding!  Exactly what I needed!

Thanks so much!!!

Todd
Thanks for the points and thanks for using EE, ~Ray