-1

I need to call a post method containing complex body data:

{
    "client": {
      "clientId":      "yourcompanyname",
      "clientVersion": "1.5.2"
    },
    "threatInfo": {
      "threatTypes":      ["MALWARE", "SOCIAL_ENGINEERING"],
      "platformTypes":    ["WINDOWS"],
      "threatEntryTypes": ["URL"],
      "threatEntries": [
        {"url": "http://www.urltocheck1.org/"},
        {"url": "http://www.urltocheck2.org/"},
        {"url": "http://www.urltocheck3.com/"}
      ]
    }
  }

I found different examples using curl and using stream_context_create but all examples simply use an array as body data. None had a complex json-structure as needed in my example. How can this be achieved?

Ole Albers
  • 8,715
  • 10
  • 73
  • 166
  • Are you sending to the server or from the server? – Ice76 Feb 19 '19 at 19:00
  • TO the server. It is about the request not the response – Ole Albers Feb 19 '19 at 19:00
  • Isn't this the same question as https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl? Can't you just **json_encode** your data? – Chin Leung Feb 19 '19 at 19:02
  • 1
    @OleAlbers Did you actually try to follow any of the examples that you found? Or did you just assume that they wouldn't do what you wanted? If you did try, please include your attempts in your question along with the results. – Patrick Q Feb 19 '19 at 19:05
  • My problem simply is that I do not have a simple flat Key/Value-Pair Structure as required by arrays, but hierarchical data. – Ole Albers Feb 19 '19 at 19:10
  • @OleAlbers What you have is perfectly fine for posting as JSON. I suggest you review some questions about posting raw JSON via curl, and take some time to make an attempt. – Patrick Q Feb 19 '19 at 19:14
  • Possible duplicate of [Curl and PHP - how can I pass a json through curl by PUT,POST,GET](https://stackoverflow.com/questions/21271140/curl-and-php-how-can-i-pass-a-json-through-curl-by-put-post-get) also [this](https://stackoverflow.com/questions/44882777/php-curl-using-post-raw-json-data) – Patrick Q Feb 19 '19 at 19:15

1 Answers1

1

Try :

$ch=curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) );
curl_setopt($ch, CURLOPT_POST, true);
// not necessarily but ... 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);

$result = curl_exec($ch);
curl_close($ch);
Vencendor
  • 132
  • 1
  • 4