I have to post values having single quote inside the string to a url using curl, single quote automatically stripped I think, how do I properly include single quote in strings while using curl,
$url = "test.com/req?a=10&b='1010','1012'";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
Use urlencode.
$url = "test.com/req?a=10&b=" . urlencode("'1010','1012'");
This way you can build query string of any complexity:
$url = 'test.com/req';
$query = array(
'a' => 10,
'b' => "'1010','1012'"
);
$url .= '?'. http_build_query($query);
// will produce this
// test.com/req?a=10&b=%271010%27%2C%271012%27
Related
$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.
Using PHP CURL i'm calling one URL and i'm getting some response from one page,Now I need to replace one string from that response but it's not working,please check my code below.
$url = "My URL";
$url1 = $url1 = str_replace(' ', '%20', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$raw_data1 = curl_exec($ch);
curl_close($ch);
$raw = str_replace('#', 'Test', $raw_data1);
echo $raw;
You are trying to replace special character,My suggestion is you should try to use preg_replace() instead of str_replace()
Try the below example:
$url = "My URL";
$url1 = $url1 = str_replace(' ', '%20', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$raw_data1 = curl_exec($ch);
curl_close($ch);
$raw = preg_replace("([#]+)", "Test", $raw_data1);
echo $raw;
To replace a pattern of string always use preg_replace() and in your case the response is coming from other source so better way to replace the string is to find define a pattern and replace Using preg_replace()
This is what you need preg_replace("([#]+)", "test", $raw_data1);
I have rest API of Nodejs Server, I'm trying to make a POST call to it using PHP.
My php code is:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I have tried calling this function with diff forms of data:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
OR
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
But on server side which Node.js, when I console log req.body I get data like this:
{ '{"_id":"111"}': '' }
How should I pass the data in PHP so I can get proper obj in node.js i.e:
{ '_id': '111' }
See the PHP document:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_POST:
TRUE to do a regular HTTP POST. This POST is the normal
application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS:
If value is an array, the Content-Type header will be set to multipart/form-data.
So you can pass a query string returned by http_build_query() into CURLOPT_POSTFIELDS:
post_url('/CCTRequest/get', http_build_query($g, null, '&'));
and remove curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));. (In fact, the varieble should be $ch, but you typed $curl, so this line doesn't work.)
In the other way, you can replace curl_setopt($ch, CURLOPT_POST, 1); with
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');, it can prevent the data be encoded automaticlly. And then send json_encode() data.
I have solved by using http_build_query($g, null, '&') for making data.
$g = array("_id" => "111");
$g = http_build_query($g, null, '&');
$postapiresponse = post_url('/CCTRequest/get', $g);
You have a typo in the code, which will prevent it setting the header $curl should be $ch:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
You also need CURLOPT_RETURNTRANSFER uncommented.
function post_url($apiRoute, $data) {
$request_url = 'www.example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I'm in the process of testing the new Bing Custom Search using below PHP code. The result is a blank white screen with no errors. Is it because this service is still in beta mode?
<?php
$sURL = "https://api.cognitive.microsoft.com/bingcustomsearch/v5.0/search?q=dogs&customconfig=[mycustomconfigvalue]&responseFilter=Webpages&mkt=en-us&safesearch=Moderate";
$key = "[myPrimaryKey]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
?>
When I try to verify if API keys are working for me using Postman, I get an error saying "Could n ot get any response".
However, if I try the same values in https://customsearch.ai under endpoint section, it works perfectly by displaying the response.
Can anyone please let me know I can't run the code using my own PHP code?
Thanks
3 Errors:
1 - CURLOPT_HEADER is different from CURLOPT_HTTPHEADER.
2 - CURLOPT_HTTPHEADER takes an array as argument, not a string.
3 - Variables ($key) only expand inside double quotes.
Try:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, 1); # you may want increase this value
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["ocp-apim-subscription-key:$key"]);
$content = curl_exec($ch);
I replied this somewhere. Here is a working php snippet. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG.
$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);
I am working with an OAuth API. Originally, I was making a header redirect once I received my $token than aggregating all of theGET parameters that were passed back to me. I'm trying to implement curl instead so I don't have to redirect back and forth. My problem is, I don't know how to retrieve the returned GET parameters after making my curl request. Here's my code
$qry_str = "?oauth_token=" . $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GSAPI_AUTHORIZE_ENDPOINT . $qry_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
I've realized I don't need $content. What I need is the GET parameters which should be passed back when I imagine occurs when initiating curl_exec. How do I retrieve these?
-
What you need to do is get the curl request to return the headers as part of the return string. You then need to parse them for the "Location:" tag and use some of the built in parse functions within PHP to get the data you want. Try the below.
$qry_str = "?oauth_token=" . $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GSAPI_AUTHORIZE_ENDPOINT . $qry_str);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
if(!$content) echo 'Curl error: ' . curl_error($ch);
preg_match('/Location\:\s(.*)\s/',$content,$matches);
$urlParts = parse_url(trim($matches[1]));
parse_str($urlParts['query'],$queryArray);
The $queryArray variable should now contain all of the query string parameters from the URL in the "Location:" field of the header.
EDIT:
This will work if you hitting a script at http://www.someurl.com/oauth.php and it's then redriecting to http://www.someotherurl.com/somescript.php?param1=x¶m2=y.
The result of $queryArray will be array("param1" => 1, "param2" => 2), although I may have completely mis-understood your question...