Biribu
Biribu

Reputation: 3833

POST to REST server by php

I want to make a post to a server I have by using php.

I was thinking in curl but all examples I find, urlfy data and I have to send a json file but not in the url.

I already have the json in an array : 'key'=>'value'...

I have to add headers, I think I can with this:

curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue','HeaderName2: HeaderValue2'));

but I don't knoe how to add my array and post it.

Any idea?

I need to add a json like this:

[{"a":"q",
  "b":"w",
  "c":[{
        "e":"w",
         "r":"t"
      }]
}]

Upvotes: 1

Views: 150

Answers (1)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

Here how you can post the data using CURL, and as you mentioned you already have a json you can do so as

$ch = curl_init(); 
curl_setopt( $ch, CURLOPT_URL, 'your api end point');
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // $postfields is the json that you have
$request_headers = array();
$request_headers[] = 'HeaderName: HeaderValue','HeaderName2: HeaderValue2';
$request_headers[] = 'Content-Type: application/json','Content-Length: ' . strlen($postfields) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers); 
$response = curl_exec($ch);
curl_close ($ch);

Upvotes: 1

Related Questions