0

I typically send an array of strings using CURL in PHP, something like this:

$data = array(
"key1" => $value,
"key2" => $value,
"key3" => $value,
"key4" => $value     

);

Then, among other curl_setop settings, post using:

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

This all works fine. But now in addition to those strings, I have 1 dataset that is JSON encoded and I want to post it at the same time. JSON looks like this:

Array ( [ad_info] => {"MoPubAdUnitInteractions":"a","MoPubAdUnitConversations":"b","MoPubAdUnitGroups":"c"} )

I think I figured out how to do it by setting a header saying I'm going to be passing in JSON like this:

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

But then, can I simply add another line for the post, but in this case the JSON encoded value like this:

curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);

I'm kinda shooting in the dark, any suggestions on how I should be thinking about this?

Ok, here is the full example:

From Processing The Form Post:

$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);    

$data = array(
  "name" => $community_name,
  "apns_name" => $community_apns_name,
  "download_url" => $community_download_url,
  "open_tagging" => $community_open_tagging, 
  "pull_content" => $community_pull_content,
  "push_content" => $community_push_content,                  
);

$json_data = array("ad_info" => $community_ad_info);
$api_querystring = $gl_app_api_url . "communities";

$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null, $json_data);

And the Function in PHP I'm calling to do the CURL:

function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {

    if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
        global $gl_community_id;
        $community_id = $gl_community_id;
    }
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PATCH":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    // Disable the SSL verificaiton process
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    if ($device_id)
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));

    if ($community_id)
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));         

    if ($json_data)
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);

    // Confirm cURL gave a result, if not, write the error
    $response = curl_exec($curl);

    if ($response === FALSE) {
        die("Curl Failed: " . curl_error($curl));
    } else {
        return $response;
    }
}

Any help is greatly appreciated.

6
  • Why don't you try it yourself first and see what happens ? Commented Oct 18, 2014 at 8:38
  • Well, I try to post only as a last resort, and after futzing with it for 2 hours I figured I'd ask for some help. Thanks @KanishkaPanamaldeniya Commented Oct 18, 2014 at 8:45
  • Without the code we only can guess about your problem Commented Oct 18, 2014 at 8:48
  • Updated the question with full code example @hindmost thanks. Commented Oct 18, 2014 at 8:54
  • 1
    Will that mean only my $json_data gets posted and my other $data is gone? I need to post both. Do I need to process the function twice then @hindmost Commented Oct 18, 2014 at 9:09

2 Answers 2

1

You use wrong approach. Setting CURLOPT_POSTFIELDS option twice doesn't lead to result you expected since each setting call discards effect of previous one.

Instead of this, you have to append extra data ($community_ad_info) to the main POST data ($data) before passing it to CURLOPT_POSTFIELDS option.

...
$community_ad_info = json_encode($_POST["ad_info"]);    

$data = array(
  "name" => $community_name,
  "apns_name" => $community_apns_name,
  "download_url" => $community_download_url,
  "open_tagging" => $community_open_tagging, 
  "pull_content" => $community_pull_content,
  "push_content" => $community_push_content,
  "ad_info" => $community_ad_info
);

$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
...
Sign up to request clarification or add additional context in comments.

2 Comments

this makes sense, but would you mind providing a bit more around the syntax/formatting for the CURLOPT_POSTFIELDS line in the function?
Figured out how to post it in addition to the string content, but it's still going in as a string. I end up with this in the JSON response. It adds the slashes between the dictionary elements @hindmost "ad_info": "{\"MoPubAdUnitInteractions\":\"AAA\",\"MoPubAdUnitConversations\":\"BBB\",\"MoPubAdUnitGroups\":\"CCC\"}",
0

This is untested of course but it should do what you need.

function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {

if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
    global $gl_community_id;
    $community_id = $gl_community_id;
}
$curl = curl_init();

switch ($method)
{
    case "POST":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

        if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        break;
    case "PUT":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');

        if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        break;
    case "PATCH":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');

        if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        break;
    default:
        if ($data)
            $url = sprintf("%s?%s", $url, http_build_query($data));
}

// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

if ($device_id)
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));

if ($community_id)
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));         



// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);

if ($response === FALSE) {
    die("Curl Failed: " . curl_error($curl));
} else {
    return $response;
}

}

And now the actualy logic

$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);    

$data = array(
  "name" => $community_name,
  "apns_name" => $community_apns_name,
  "download_url" => $community_download_url,
  "open_tagging" => $community_open_tagging, 
  "pull_content" => $community_pull_content,
  "push_content" => $community_push_content,                  
  "ad_info"      => $community_ad_info
);

$api_querystring = $gl_app_api_url . "communities";

$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);

The things to note here are,

the new content tyoe header tells it to be processed as a form post.

removal of the $json_data array, the "ad_info" key is not just added into the $data array

When you process this on the other side you can access the ad_info like this

$ad_info = json_decode($_POST['ad_info']);

You can access the other fields with

$apns_name = $_POST['apns_name'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.