CURL POSTFIELDS to contain "&" character - php

I have working SMS sending over gateway using CURL method.
But If I include this character "&" in my message text area, it will send the message before this character only.
So how I could fix it to send messages including this character normally.
here is my code:
$from = "Gateway_username"; // SMS username
$token = "Gateway_password"; // SMS password
$option = $_REQUEST["option"];
$text = $_REQUEST["BulkSMS1__messageTextBox"];
if ($text == "") { } else {
$url = "http://awaljawaly.awalservices.com.sa:8001/Send.aspx";
$postfields = array ("REQUESTTYPE" => "SMSSubmitReq",
"Username" => "$from", "Password" => "$token", "MOBILENO" => "$d_mobile", "MESSAGE" => "$text");
if (!$curld = curl_init()) {
echo "Could not initialize cURL session.";
exit;
}
curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($curld, CURLOPT_URL, $url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curld);
curl_close ($curld);
preg_match("/(.*)/",$output, $out);
}
This is a sample message:
Our Address: H&R Center.
Thanks in advance.
I have used this to fix my issue:
$text = str_replace('&', '%26', $_REQUEST["BulkSMS1__messageTextBox"]);

You would want to encode the characters:
http://www.clockworksms.com/blog/the-gsm-character-set/
With this, try using:
utf8_encode()
The reason for this is that you're encoding for a mobile device, not a website, so using url encode will not work, compared to utf8 encode.

See urlencode() -> http://php.net/manual/en/function.urlencode.php
<?php
$text = urlencode($_REQUEST["BulkSMS1__messageTextBox"]);
?>

I have used this to fix my issue:
$text = str_replace('&', '%26', $_REQUEST["BulkSMS1__messageTextBox"]);

Related

PHP - json_decode - issues decoding string

I'm playing with the API from deepl.com that provides automatic translations. I call the API through cURL and I get a json string in return which appears to be fine but cannot be decoded by PHP for some reason.
Let me show first how I make the cURL call :-
$content = "bonjour <caption>monsieur</caption> madame";
$url = 'https://api.deepl.com/v2/translate';
$fields = array(
'text' => $content,
'target_lang' => $lg,
'tag_handling' => 'xml',
'ignore_tags' => 'caption',
'auth_key' => 'my_api_key');
$fields_string = "";
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Content-Length: '. strlen($fields_string)));
$result = curl_exec($ch);
curl_close($ch);
If at this stage I do
echo $result;
I get:
{"translations":[{"detected_source_language":"FR","text":"Hola <caption>monsieur</caption> Señora"}]}
Which seems ok to me. Then if I use code below -
echo gettype($result);
I get "string" which is still ok but now, the following code fails:
$result = json_decode($result,true);
print_r($result);
The output is empty!
If I now do something like this:
$test = '{"translations":[{"detected_source_language":"FR","text":"Hola <caption>monsieur</caption> Señora"}]}';
echo gettype($test);
$test = json_decode($test,true);
print_r($test);
I get a perfectly fine array:
(
[translations] => Array
(
[0] => Array
(
[detected_source_language] => FR
[text] => Hola <caption>monsieur</caption> Señora
)
)
)
I did nothing else than copy/pasting the content from the API to a static variable and it works but coming from the API, it doesn't. It's like the data coming from the API is not understood by PHP.
Do you have any idea of what's wrong?
Thanks!
Laurent
I've had very similar issues before and for me the issue was with the encoding of the data returned from an API being unicode. I'm guessing when you do your copy/paste the string you hard-code ends up being a different encoding so it works fine when passed into json_decode.
The PHP docs specify json_decode only works with UTF-8 encoded strings:
http://php.net/manual/en/function.json-decode.php
You may be able to use mb_convert_encoding() to convert to UTF-8:
http://php.net/manual/en/function.mb-convert-encoding.php
Try this before calling json_decode:
$result = mb_convert_encoding($result, "UTF-8");
Make sure to set CURLOPT_RETURNTRANSFER to true. Only then will curl_exec actually return the response, otherwise it will output the response and return a boolean, indicating success or failure.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result !== false) {
$response = json_decode($result, true);
// do something with $response
} else {
// handle curl error
}
Like said #Eilert Hjelmeseth you have some special char in your JSON string => "Señora"
Another way to encode a string to UTF8: utf8_encode() :
$result = json_decode(utf8_encode($result),true);

Sending XML post request using API

I am attempting to make an xml post request which hit the other server url and post xml data their but the code not working for me here is my code
if ($mail->send()) {
$URL = "server link api based";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml','Content-Length: ' . strlen($xml)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
// echo $output;
if ($output) {
echo "1";
} else {
echo "2";
}
}
} catch (Exception $e) {
echo $e;
}
XML format of data here is the code of xml format
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<data>
<lead>
<key>YaskjdfweuYksdlksid....</key>
<leadgroup>.....</leadgroup>
<site>.....</site>
<introducer>0</introducer>
<source>FDH Quick submission</source>
<medium>FDH Quick submission</medium>
<firstname>' . $firstName . '</firstname>
<lastname>' . $lastName . '</lastname>
<email>' . $userEmail . '</email>
<postcode>' . $postCode . '</postcode>
<contactphone>Yes</contactphone>
<phone1>' . $userPhoneNo . '</phone1>
</lead>
</data>';
1 possible issue is that you're not escaping your strings as you insert them in your XML, which might leave you with a corrupt XML file (eg, & must be escaped as &, < must become <, ' must become &apos;, and so on)
you can xml-encode strings with this function:
function xml_esacpe(string $str, string $charset = 'UTF-8'): string {
if (! strlen ( $str )) {
return "";
}
$ret = htmlspecialchars ( $str, ENT_QUOTES | ENT_SUBSTITUTE | ENT_DISALLOWED | ENT_XML1, $charset, true );
if (! strlen ( $ret )) {
throw new Exception ( "failed to xml-encode input! (most likely wrong charset or corrupted input)" );
}
return $ret;
}
furthermore, you can verify that your XML is valid by doing $isValidXML=#((new DOMDocument())->loadXML($xml)); - it will now be true if the xml is valid, or false if the xml is invalid. - is the xml you're sending actually valid xml?
but in any case, you must elaborate what you mean by the code not working for me - how is it not working?

SMS GATEWAY ISSUE in PHP

I am integrating SMS gateway for the very first time. I want to send sms when someone pays to the website. I am using the following code:
<?php
$pay="1000";
$msg="Arivind";
echo $url="http://yourdomainname.com/api/swsend.asp?username=xxxxxx&password=xxxxxx&sender=SENDERID&sendto=91XXXXXXXXX&message=Dear'$msg' Thanks for making payment of Rs '$pay'";
$c=curl_init();
curl_setopt($c,CURLOPT_RETURNTRANSFER,1);
curl_setopt($c,CURLOPT_URL,$url);
$contents=curl_exec($c);
curl_close($c);
echo "SMS Successfully sent";
?>
Now if i am using variable in body of message, the message is not sent but if i use static message the message is getting delivered to the number.
The static message doesnt solve my purpose as i need the message to be sent to different person, the variable used ie $msg will have different name of people & fetched from database.
KINDLY SUGGEST.
Using variables between single quotes ' does not convert it into dynamic values. Also its better to RestApi in simple PHP function:
function CURLcall($number, $message_body){
$api_params = "swsend.asp?username=xxxxxx&password=xxxxxx&sender=SENDERID&sendto=91XXXXXXXXX&message=$message_body";
$smsGatewayUrl = "echo $url="http://yourdomainname.com/api/";
$smsgatewaydata = $smsGatewayUrl.$api_params;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, smsgatewaydata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
// Use file get contents when CURL is not installed on server.
if(!$output){
$output = file_get_contents($smsgatewaydata);
}
}
Call above function as:
$message_body = urlencode("Dear $msg Thanks for making payment of Rs $pay");
CURLcall('918954xxxxx',$message_body);
Please note: urlencode is useful to avoid errors in GET method as it convert space into encoded format http://php.net/manual/en/function.urlencode.php
You can also use http_build_query to convert your variables into a nicely formatted URL.
<?php
$fname = 'Matthew';
$lname = 'Douglas';
$amount = 1000;
$message = "Thanks for your payment of Rs {$amount}.";
$urlComponents = array(
'firstName' => $fname,
'lastName' => $lname,
'message' => $message
);
$url = 'http://yourdomainname.com/api/swsend.asp?';
echo $url . http_build_query($urlComponents);
?>

How to make curl call for remote url which contain space

This question is continuation of my previous question
<?php
$remoteFile = 'http://cdn/bucket/my textfile.txt';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
print_r($data)
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}
$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
$status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>
I am using above code to get the file size in server side from CDN url but when I use the CDN url with space in it. it is throwing below error
page not found 09/18/2014 - 16:54 http://cdn/bucket/my textfile.txt
Can I make curl call for remote url which contain space ?
To give little bit more info on this
I am having interface where user will be saving file to CDN (so user
can give whatever title user want, it may contain space )and all
information in saved in back end db. I have another interface where I
retrieve the saved information and show it in my page along with file
size which I am getting using above code.
You have to encode your url's which have space's in it.
echo urlencode('http://cdn/bucket/my textfile.txt');
Ref: urlencode
or you can use,
echo '<a href="http://example.com/department_list_script/',
rawurlencode('sales and marketing/Miami'), '">';
Ref: rawurlencode
Yes you need to URL / URI encode
In an encoded URL, the spaces are encoded as: %20, so your URL would be: http://cdn/bucket/my%20textfile.txt so you could just use this url.
Or as this is PHP, you could use the urlencode function.
ref: http://php.net/manual/en/function.urlencode.php
e.g.
$remoteFile = urlencode('http://cdn/bucket/my textfile.txt');
or
$ch = curl_init(urlencode($remoteFile));

PHP (CI) cURL passed multidimensional array does not behave as one (Can't loop it)

I'm having an extrange issue when receiving parameters from a POST cURL request. No matter how I encode it (json, url, rawurl, utf8, base64...) before POSTing it, I am not able to perform any decoding operation through the array elements, via loop. I'm giving you the details.
From the consuming controller, in some other php (Yii) app, I build my request like this:
private function callTheApi($options)
{
$url = "http://api.call.com/url/api";
$params = array( 'api_key' => $this->api_key,
'domain' => $this->domain,
'date' => $options['date'],
'keys' => $options['keys'] // This is an array
);
// Following some good advice from Daniel Vandersluis here:
// http://stackoverflow.com/questions/3772096/posting-multidimensional-array-with-php-and-curl
if (is_array($params['keys'])
{
foreach ($params['keys'] as $id => $name)
{
$params['keys[' . $id . ']'] = $name;
}
unset($params['keys']);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data; charset=utf-8'));
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en; rv:1.9.0.4) "
. "Gecko/2009011913 Firefox/3.0.6");
$output = curl_exec($ch);
$error = curl_errno($ch);
$error_text = curl_error($ch);
curl_close($ch);
if (!$output || $error != 0)
die("<br><hr>Problems...<br>"
. "Line:" . __LINE__ . " dataExtractor.php<br>"
. "Error: " . $error . " - " . $error_text . "<hr>"
. $url . "<hr>");
sleep(1);
return json_decode($output, true);
}
And in the api itself, this is the function:
public function api()
{
$params = $_POST;
foreach($params as $k=>$v){
if($k=='domain') $domain = $v;
if($k=='date') $date = $v;
if($k=='api_key') $api_key = $v;
if($k=='keys') $keys = $v;
}
echo json_encode($keys);
// All my logic would be here, after parsing the array correctly.
}
Ok, now for the problems:
If i leave everything like stated before, it works. I have my $keys array in the api, and I can use it however I want. The "echo json_encode($keys)" sentence returns the array ALMOST as it should be. But the problem is some values of the array are corrupted in the cURL operation. Values such as spanish characters á, é ,í, ó, ú OR ü are simply not present in the array_values.
If some key in the $keys array was spanish word "alimentación" in the original array, once it's been cURLed to the api, it becomes "alimentacin". There, the ó is not there anymore.
So, my chances are encoding each value in the array to a safely transferred value, so that I can decode it later. But what do you know, I can't.
I've tried urlencoding, rawurlencoding, json_encoding, base64_encoding... each value of the array. And if I return the received array from the api, it contains the encoded values all right. BUT.
If I loop the array in the api for decoding, and then try to return it, no matter what decoding function I'm applying to its values, the output is ALWAYS "NULL".
I have no clue what I'm doing wrong here. Not even close.
So any help would be much appreciated. Thanks in advance, community.
When you create cUrl params array you should know that keys cannot be utf8.
And when you add some parameters in foreach loop
$params['keys[' . $id . ']'] = $name;
$id can be utf8 character.
To avoid that I recommend you to use json_encode
$params = array(
'api_key' => $this->api_key,
'domain' => $this->domain,
'date' => $options['date'],
'keys' => json_encode($options['keys']) // This is an array
);
In your api in this case you should change nothing.

Categories