Reputation: 158
I am trying to send a php post request to my rocket chat server, I was able to do that using curl from command line by using this command from rocket chat api:
curl -H "X-Auth-Token: xxxxx" -H
"X-User-Id: yyyyy" -H "Content-type:application/json"
http://example:3000/api/v1/chat.postMessage -d '{ "channel":
"#general", "text": "Halo from Germany" }'
But using php I never succeed to do that (by using curl or without)
The following php code return false:
<?php
$url = 'http://example:3000/api/v1/chat.postMessage';
$data = json_encode(array('channel' => '#general', 'text' => 'Halo from Germany'));
$options = array( 'http' => array( 'header' => 'Content-type: application/json', 'X-Auth-Token' => 'xxxxx', 'X-User-Id' => 'yyyyyy', 'method' => 'POST', 'content' => http_build_query($data) ) );
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
?>
Thank you for your help
Upvotes: 1
Views: 1368
Reputation: 21513
php has a (parital) wrapper for libcurl, the same library that the curl cli program use under the hood to do requests, you can just use libcurl from php.
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_HTTPHEADER => array (
"X-Auth-Token: xxxxx",
"X-User-Id: yyyyy",
"Content-type:application/json"
),
CURLOPT_URL => 'http://example:3000/api/v1/chat.postMessage',
CURLOPT_POSTFIELDS => json_encode ( array (
"channel" => "#general",
"text" => "Halo from Germany"
) )
) );
curl_exec ( $ch );
curl_close($ch);
Upvotes: 1