What does (-X,-H,-d) mean for this command (Curl -X POST -H "Content-Type: application/json" -d) and how to do it for the php file?

Asked

Viewed 2,199 times

2

curl -X POST -H "Content-Type: application/json" -d

I need to do this command and send a JSON to a certain API that will return a response but I don’t know how the structure of this would look in a PHP file and what this data means (-X -H -d). I’ve seen it look like that when we do the remote cmd.

1 answer

2


curl -X POST -H "Content-Type: application/json" -d

According to the documentation:

  • -X: Specifies the request method (GET, HEAD, POST or PUT) to use when communicating with the server.

  • -H: Indicates that a Header extra will be included in the request.

  • -d: Send the data specified in a request POST to the server.

In PHP it would look something like this:

$curl = curl_init();
$url = "URL";

curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$resultado = curl_exec($curl);
curl_close($curl);

print_r($resultado);

If you want to send more data in this request, you need to use the function json_encode() to code them properly. See an example:

$foo = "foo";
$bar = "bar";

$dadosJson = json_encode(array( "foo"=> $foo, "bar" => $bar));
curl_setopt($curl, CURLOPT_POSTFIELDS, $dadosJson);
  • @Josiel Funciona?

  • @Josiel Post the code on www.pastebin.com and put the link here!

  • sorry the delay I’m learning to use the site yet. It was the first question I asked and I do not know how it works right... It did work ... thanks for the help... but I’m having problems with json_encode. When I use an array inside another one it transforms the two arrays into a json, while actually the inside one should remain as an array containing json inside...

  • @Josiel No problem, enjoy and make a tour (http://answall.com/tour) on the website. As for json_encode it is advisable to ask another question about this!

  • @And as soon as possible mark this answer as "accepted" by clicking on the arrow below the answer score!

  • 1

    OK ... I will do yes to learn how to use the tool correctly... Qt to json I will ask another question yes... thank you.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.