how to send xml file to server backend using php? [duplicate] - php

This question already has answers here:
How to properly send and receive XML using curl?
(2 answers)
Closed 9 years ago.
I have fetched data from server using this code, `$server = 'LOCALHOST:9000';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}`
Now I have to do reverse, how to send the data into server using php? curl method is the only way or is there any other method to do the same. Give me some example.

Sending/Receiving using cURL is the exact same thing. cURL is based on sending data to an given URL and possibly receiving a response. Let's take a simple example of getting a user and sending a user.
Getting a user would be
$data = array(
'user_id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/getUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
getUser.php does nothing more than search for a user and return the data found.
$response would possibly contain data of the user, perhaps just a text-response containing the name. A serialized PHP array, an XML response with a full user profile.. etc.
Inserting/Sending data
$data = array(
'user_name' => 'Joshua',
'user_email' => 'my#email.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/addUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
addUser.php performs some validation of the fields and if validated inserts a user in the database
$response in this case does not contain the userdata (however: it's a possibility), but more likely the $response contains a result. An ok textresponse, a json/xml response or perhaps a '200 OK' header response
It's all basically the same. There is no difference in getting/sending data using cURL. It's all based on sending a request and in most cases do something with the outcome.

Related

Sending bulk messages in twillo notify API via CURL (php)

$data = [];
$data['ToBinding'] = json_encode(array("binding_type"=>"sms", "address"=>"+19991112222"));
$data['Body'] ="test";
$ch = curl_init("https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXX/Notifications");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD,'XXXXXXXXXXXXXXXXXXX:XXXXXXXXXXXXXXXXXXX');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resultData = curl_exec($ch);
This code was copied from another post. I am able to get this to work just fine, using real numbers of course. However I cannot populate $data['ToBinding'] with multiple numbers, which is the whole purpose of using Twilio Notify. I have tried many different combinations of code and it blows up, most of the time with "Cannot convert incoming parameters to notification object: Parameter 'ToBinding' is invalid".
I was able to get it to at least execute without errors using this code (real numbers of course):
$data['ToBinding'] = json_encode(array("binding_type"=>"sms", "address"=>"+19991112222","binding_type"=>"sms", "address"=>"+19993334444"));
But it only sends to the first number in the array. Any help on how to populate the array to send to multiple numbers (or maybe another way using cURL) will be appreciated.
==== FULL CODE ====
$query = array("ToBinding" => array(
json_encode(array("binding_type"=>"sms", "address"=>"+19991112222")),
json_encode(array("binding_type"=>"sms", "address"=>"+19993334444"))
));
$data = http_build_query($query);
$data = preg_replace('/%5B[0-9]+%5D/simU', '', $data);
echo $data;
$data['Body'] ="Notify cURL API test";
$ch = curl_init("https://notify.twilio.com/v1/Services/<NOTIFY ID HERE >/Notifications");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD,'<ACCT ID HERE>:<TOKEN HERE >');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resultData = curl_exec($ch);
===== FINAL WORKING CODE =====
$data['Body'] ="Notify cURL API test";
$data['ToBinding'] = array(
json_encode(array("binding_type"=>"sms","address"=>"+19191112222")),
json_encode(array("binding_type"=>"sms","address"=>"+19193334444"))
);
$query = http_build_query($data);
$string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query);
$ch = curl_init("https://notify.twilio.com/v1/Services/ISxxxxxxxxxx/Notifications");
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD,'ACxxxxxxxxxx:xxxxxxxxxxxxxxxxx');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resultData = curl_exec($ch);
echo "curl Response=".$resultData."<br>";
$responseHttp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
Twilio developer evangelist here.
The ToBinding parameter is an array of binding objects. Notify implements support for that by decoding multiple ToBinding parameters from the request.
The curl example from the Notify documentation looks like this:
curl -X POST https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications \
--data-urlencode 'ToBinding={"binding_type":"sms", "address":"+15555555555"}' \
--data-urlencode 'ToBinding={"binding_type":"facebook-messenger", "address":"123456789123"}' \
-d 'Body=Hello Bob' \
-u 'your_account_sid:your_auth_token'
As you can see, there are two ToBinding parameters included in the data.
As far as I can tell, PHP doesn't support building the body like that. http_build_query appears to be useful, but builds arrays of data using name[index] form, which we don't want. You can strip the [index] out though, with something like the following:
$query = array("ToBinding" => array(
json_encode(array("binding_type"=>"sms", "address"=>"+19991112222")),
json_encode(array("binding_type"=>"sms", "address"=>"+19993334444"))
));
$data = http_build_query($query);
$data = preg_replace('/%5B[0-9]+%5D/simU', '', $data);
echo $data;
# => ToBinding=%7B%22binding_type%22%3A%22sms%22%2C%22address%22%3A%22%2B19991112222%22%7D&ToBinding=%7B%22binding_type%22%3A%22sms%22%2C%22address%22%3A%22%2B19993334444%22%7D
Let me know if this helps at all.

Send message button in facebook bot PAGE

good evening,
I'm already breaking my head for 3 days I'm trying to send a message with the button from a page with a bot made in CURL PHP
I'm trying with CURL and PHP POST GRAPH
without success both of us can help me?
function SendRawResponse($Rawresponse){
$userPageConversation = 't_100005050355547';
$Access_token = "XXXX";
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;
//$url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$Access_token;
$ch = curl_init($url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'charset=utf-8',
);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $Rawresponse);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Rawresponse));
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse));
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
$erros = curl_errno($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($erros);
var_dump($response);
curl_close($ch);
}
Mensage:
$teste = '{
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Try the postback button!",
"buttons":[
{
"type":"web_url",
"title":"GOOGLE",
"url":"https://www.google.com.br"
}
]
}
}
}}';
SendRawResponse($teste);
erros:
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse)); = Missing message body
According to the docs
you must add domain to the whitelist in FB page settings.
Domains must meet the following requirements to be whitelisted:
Served over HTTPS
Use a fully qualified domain name, such as
https://www.messenger.com/. IP addresses and localhost are not
supported for whitelisting.

Passing JSON to PHP CURL [duplicate]

I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

How to Add Recipient to Sendgrid v3 API with PHP

What I'm looking to do is add a single recipient to sendgrid when they signup on my site. Once they're added, I will then email the user and add them to a list.
But I'm having trouble adding the user to Sendgrid.
Their documentation (https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Add-Recipients-POST) says to add a user you need to POST their details here:
https://api.sendgrid.com/v3/contactdb/recipients
add_user_new($email);
function add_user_new($email) {
$url = 'https://api.sendgrid.com/v3/contactdb/recipients';
$params =array( array(
//'name' => 'this is a reserved field',
'email'=> 'info#domain.com'
));
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init($request);
$headers = array("Authorization: Bearer api_key_here");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
echo $json_post_fields;
}
This is the response I get, not sure what I'm missing. The error they say is because the JSON is invalidly formatted.
string(51) "{"errors":[{"message":"request body is invalid"}]}
This is what my JSON looks like:
{"name":"hello#test.com"}
Encode your $json_post_fields variable do in JSON format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_post_fields));

Error when doing cURL request

This code always returns user doesn't exist from the API:
$data2 = array('user'=>$vars['mcusername'],
'pwd'=>$vars['mcpassword'],
'group'=>$postfields['group'],
'action'=>'Save');
// Connect to dvb API
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?part=userconfig&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
$data = curl_exec($ch);
curl_close($ch);
The string that works in a browser is this:
dvbapi.html?part=userconfig&user=PeterTest&pwd=obfuscated&group=1,2&disabled=0&action=Save
When you access the URL in the browser, you're performing a GET. In your cURL attempt, you're attempting to POST. This is likely the issue; the script may only accept GET.
Try using this cURL code instead:
// Gather up all the values to send to the script
$data2 = array('part' => 'userconfig',
'user' => $vars['mcusername'],
'pwd' => $vars['mcpassword'],
'group' => $postfields['group'],
'action' => 'Save');
// Generate the request URL
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?".http_build_query($data2);
// cURL the URL for a responce
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
// Show the responce
var_dump($data);
You can use http_build_query() to turn your array into a URL-encoded string to make the GET request.

Categories