CURL PHP POST interferes with JSON - php

I currently have an API script that returns JSON. It has worked up until I tried to add in a curl php POST script before it. The curl script is working on it's own, and it is also working in the API script. However the JSON code is not being returned.
Is there something fundamentally wrong with this approach below?
Thanks in advance.
EDIT: The curl script works 100% on its own.
Said script is also working inside the below, it's just that the JSON does not return.
$name = "foo";
$age = "bar";
//set POST variables
$url = 'https://www.example.com';
$fields = array(
'name' => urlencode($name),
'age' => urlencode($age)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return json_encode(
array(
"status" => 1,
"message" => "Success!",
"request" => 10
)
);

You need to do the following use echo and also use CURLOPT_RETURNTRANSFER if not the output would be transferred directly to the page instead of $result
$name = "foo";
$age = "bar";
$url = 'http://.../a.php';
$fields = array('name' => urlencode($name),'age' => urlencode($age));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
header('Content-type: application/json');
echo json_encode(array("status" => 1,"message" => "Success!","request" => 10));

Related

Extra garbage values added when posting JSON data using cURL

I am trying to create an API using cURL & JSON.
Now In my first PHP file I am sending data as JSON data, Like below:
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
But on my SERVER where I get this request when I show (using var_export()) the values:
public function login()
{
$client_data = $this->input->post();
var_export($client_data);
}
Error:
array ( '"{\u201cRequest\u201d:\u201cLogin\u201d,\u201cUsername\u201d:\u201cBIZRTC\u201d,\u201cAPIAccessKey\u201d:\u201cAW342FFGRTR56RTH\u201d,\u201cGMT-Timestamp\u201d:_\u201c1489670000\u201d}"' => '', 0 => '', )
Even if I decode it there I still get \u. Also I dont understand how are these values appended : at starting : '"{\\u201c and this \\u201d}"' => '', 0 => '', at the back.
What are these values?
How do I decode this JSON?
Am I Posting right data to Server?
Updated code
Client.php
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
Server.php
public function login()
{
var_export($_POST);
}
You need to give array in json_encode, Instead of string.
Replace:
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
To:
$field_string= '{
"Request": "Login",
"Username": "anonymous",
"APIAccessKey": "AW342FFGRTR56RTH",
"GMT-Timestamp": "1489670000"
}';
Problems in code:
Incorrect json.
Invalid quotes(”) in json.
Passing string in json_encode.
if you are storing json string in variable then you don't need the json_encode() because it is used to convert array to json string.
$field_string = '{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}';
$json = $field_string;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
it is because of below line
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
suppose to be like this
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);

post data in an array in php

I have collected data and created and array :
Array
(
[0] => Array
(
[id] => 1
[name] => Martin
[surname] => test
[email] => martin#gmail.com
[dob] => 2015-02-24
)
[1] => Array
(
[id] => 2
[name] => Kary
[surname] => paulman
[email] => kary#gmail.com
[dob] => 2015-06-26
)
)
I have multiple records in this array.
I want to post each record in the array to www.recieve.com , where it will pass a response of 'true' if post was successful and 'false' if it fails.
I have researched the interent and i dont even know where to start.
So far my code looks like this (this is just for the array)
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}
echo "<pre>"; print_r($res); echo "</pre>";
I have tryed this and it is not working :
//Build my array
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}
//URL to post to
$url = 'https://theurl.com?';
//url-ify the data for the POST
foreach($res as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
There are 2 problems with your cURL request that I can see:
You are not encoding the values correctly for use in a query string
$fields is undefined.
You can solve that using for example:
// make sure the values are encoded correctly:
$fields_string = http_build_query($res);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
// you need the count of your `$res` variable here:
curl_setopt($ch,CURLOPT_POST, count($res));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Also note that you don't need a question mark at the end of the url. I don't know if that would cause problems, but you should probably just remove that:
$url = 'https://theurl.com';
Use Curl and like this
$ch = curl_init(); // initiate curl
$url = "http://www.somesite.com/curl_example.php"; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
$output = curl_exec ($ch); // execute
curl_close ($ch); // close curl handle
var_dump($output); // show output
?>
Use your array in the : curl_setopt($ch, CURLOPT_POSTFIELDS

RingCentral PHP FaxOut API example

I just started looking at the RingCentral API
I am a little confused on how they expect the data.
I tried first with curl using:
$url = ' https://service.ringcentral.com/faxapi.asp';
$faxData = array();
$faxData['Username'] = 'xxxxxxxx';
$faxData['Password'] = 'xxxxxxxx';
$faxData['Recipient'] = $faxNumber.'|TEST';
$faxData['Attachment'] = ROOT_PATH.$fileLocation;
// build url encoded string
$fields_string='';
foreach($faxData as $key=>$value) {
$fields_string .= $key.'='.urlencode($value).'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($faxData));
curl_setopt($ch,CURLOPT_POSTFIELDS, $faxData);
//execute post
$result = curl_exec($ch);
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
//close connection
curl_close($ch);
Then I tried sending as an email using the number#ringcentral.com and I still am unable to get this to work at all. Their support site is useless as I see many unanswered questions but I have no choice and need to get this working.
I am hoping someone has done this in PHP and can provide me with an example or point me in the right path.
I was able to get the original code to work doing two things:
(1) Removing the leading space from $url:
# Original
$url = ' https://service.ringcentral.com/faxapi.asp';
# New
$url = 'https://service.ringcentral.com/faxapi.asp';
(2) Ensuring ROOT_PATH began with a # as specified in the PHP documentation for CURLOPT_POSTFIELDS at http://php.net/manual/en/function.curl-setopt.php.
cURL and Guzzle Examples
Here are some examples using cURL and Guzzle verified to work.
cURL Example
function ringcentral_faxout_api_via_curl($username,$password,$recipient,$file,$coverpagetext) {
$request = curl_init('https://service.ringcentral.com/faxapi.asp');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, array(
'username' => $username,
'password' => $password,
'recipient' => $recipient,
'attachment' => '#' . realpath($file),
'coverpagetext' => $coverpagetext
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
curl_close($request);
return $response;
}
$username = 'myusername';
$password = 'mypassword';
$recipient = 'myrecipient';
$file = '/path/to/myfile';
$result = ringcentral_faxout_api_via_curl( $username, $password, $recipient, $file, 'PHP FaxOut Via cURL');
Guzzle Example
use GuzzleHttp\Client;
function ringcentral_faxout_api_via_guzzle($username,$password,$recipient,$file,$coverpagetext) {
$client = new Client();
$response = $client->post('https://service.ringcentral.com/faxapi.asp', [
'body' => [
'username' => $username,
'password' => $password,
'recipient' => $recipient,
'attachment' => fopen($file, 'r'),
'coverpagetext' => $coverpagetext
]
]);
return $response->getBody();
}
$username = 'myusername';
$password = 'mypassword';
$recipient = 'myrecipient';
$file = '/path/to/myfile';
$result = ringcentral_faxout_api_via_guzzle( $username, $password, $recipient, $file, 'PHP FaxOut Via Guzzle');
New RingCentral API
Also check out the newer RingCentral Platform API which has a much more comprehensive API for faxing and other capabilities documented here: https://developers.ringcentral.com/api-and-docs.html
function fetch_url_post($url, $variable_array){
$fields_string = "";
//set POST variables
#$url = 'http://domain.com/get-post.php';
foreach($variable_array as $key => $value){
$fields[$key] = urlencode($value);
}
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
return $result;
//close connection
curl_close($ch);
}
$url = ' https://service.ringcentral.com/faxapi.asp';
$faxData = array();
$faxData['Username'] = 'xxxxxxxx';
$faxData['Password'] = 'xxxxxxxx';
$faxData['Recipient'] = $faxNumber.'|TEST';
$faxData['Attachment'] = ROOT_PATH.$fileLocation;
echo fetch_url_post($url, $faxData);
make sure ROOT_PATH.$fileLocation; is an absolute and correct path

Curl request response not getting

I am sending payment info to Virtual merchant payment gateway for payment system using curl. This is my code :
$Url= "https://www.myvirtualmerchant.com/VirtualMerchant/process.do";
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Include header in result? (0 = yes, 1 = no)
// curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$fields = array(
'ssl_card_number'=>urlencode($_POST['ssl_card_number']),
'ssl_exp_date'=>urlencode($_POST['ssl_exp_date']),
'ssl_cvv2cvc2'=>urlencode($_POST['ssl_cvv2cvc2']),
'ssl_avs_address'=>urlencode($_POST['ssl_avs_address']),
'ssl_avs_zip'=>urlencode($_POST['ssl_avs_zip']),
'ssl_merchant_id'=>urlencode($_POST['ssl_merchant_id']),
'ssl_user_id'=>urlencode($_POST['ssl_user_id']),
'ssl_pin'=>urlencode($_POST['ssl_pin']),
'ssl_transaction_type'=>urlencode($_POST['ssl_transaction_type']),
'ssl_amount'=>urlencode($_POST['ssl_amount']),
'ssl_show_form'=>urlencode($_POST['ssl_show_form']),
'TransactionType'=>urlencode($_POST['TransactionType'])
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Download the given URL, and return output
echo $output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
print_r($output);
But in $output i am getting nothing, not any error or message. Am i doing it wrong ? please tell me ?
First I'd check your mechant_id, pin, etc. Below is working code I created after working through a similar problem.
<html>
<body>
<p>--start--</p>
<?php
//if you have a live account don't use the "demo" post url it won't work
$post_url = 'https://www.myvirtualmerchant.com/VirtualMerchant/process.do';
//replace the xxx's with your proper merchant_id, etc.
//they will give you these when you activate your account
//I've set form to not show, and ssl_result_format =>ascii to get a string returned
$fields = array(
'ssl_merchant_id' =>'xxxxxx',
'ssl_user_id' =>'xxx',
'ssl_pin' =>'xxxxx',
'ssl_show_form' =>'false',
'ssl_result_format' =>'ascii',
'ssl_test_mode' =>'false',
'ssl_transaction_type' =>'ccsale',
'ssl_amount' =>'1.44',
'ssl_card_number' =>'5000300020003003',
'ssl_exp_date' =>'1214',
'ssl_avs_address' =>'Test 3',
'ssl_avs_zip' =>'123456',
'ssl_cvv2cvc2' =>'123',
);
//build the post string
$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .=$key.'='.$value.'&'; }
rtrim($fields_string, "&");
//open curl session
// documentation on curl options at http://www.php.net/curl_setopt
$ch = curl_init();
//begin seting curl options
//set URL
curl_setopt($ch, CURLOPT_URL, $post_url);
//set method
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//set post data string
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//these two options are frequently necessary to avoid SSL errors with PHP
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
if($result === FALSE) {
//post failed
die(curl_error($ch));
} else {
//got a response
//some people seem to get name/value pairs delimited with "&"
//but currently mine is \n
//support told me there's no way to change it..
$response_array = explode("\n",$result);
//make it nice and useful
foreach( $response_array as $k=>$v ){
$v=explode("=",$v);
$a[$v[0]]=$v[1];
}
//show the whole array
print_r($a);
//use a specific return value
//returns "APPROVAL" if it went through
echo('<h1>'. $a[ssl_result_message] . '</h1>');
}
?>
<p>--end--</p>
</body>
</html>
The code above should net you a screen like this:
--start--
Array ( [ssl_card_number] => 50**********3003 [ssl_exp_date] => 1214 [ssl_amount] => 1.44 [ssl_customer_code] => [ssl_salestax] => [ssl_invoice_number] => [ssl_description] => [ssl_departure_date] => [ssl_completion_date] => [ssl_company] => [ssl_first_name] => [ssl_last_name] => [ssl_avs_address] => Test 3 [ssl_address2] => [ssl_city] => [ssl_state] => [ssl_avs_zip] => 123456 [ssl_country] => [ssl_phone] => [ssl_email] => [ssl_result] => 0 [ssl_result_message] => APPROVAL [ssl_txn_id] => AA49315-1234567-F78F-468F-AF1A-F5C4ADCFFB1E [ssl_approval_code] => N53032 [ssl_cvv2_response] => [ssl_avs_response] => [ssl_account_balance] => 0.00 [ssl_txn_time] => 01/15/2014 11:53:15 AM )
APPROVAL
--end--
Make sure you delete all these test purchases when you finished testing. I'm told they will inhibit your real purchases from posting.
try this to find out the error
var_dump(curl_error($ch));
before and calling curl_exec($ch);
You are calling an HTTPS page. Please refer to following link
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Try to find error give this code before curl close:--
echo "Curl Error :--" . curl_error($ch);
if no error found do like this:-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
then
print_r($result);
exit;
Try this:
$output = curl_exec($ch);
$response = curl_getinfo($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
Hope you get the response :)

How to send XML and other post parameters via cURL in PHP

I've used code below to send XML to my REST API. $xml_string_data contains proper XML, and it is passed well to mypi.php:
//set POST variables
$url = 'http://www.server.cu/mypi.php';
$fields = array(
'data'=>urlencode($xml_string_data)
);
//url-ify the data for the POST
$fields_string = "";
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
echo $fields_string;
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
"Expect: "
));
//execute post
$result = #curl_exec($ch);
But when I've added other field:
$fields = array(
'method' => "methodGoPay",
'data'=>urlencode($xml_string_data)
);
It stopped to work. On the mypi.php I don't recieve any more POST parameters at all!
Could you you please tell me what to do to send XML and other post parameters in one cURL request?
Please don't suggest using any libraries, I wan't to acomplish it in plain PHP.
I don't see anything wrong with this script. It's most likely an issue with mypi.php.
You do have an extra & at the end. Maybe that confuses the server? The rtrim doesn't change the $field_string and it returns the trimmed string.
The postfields can be simplified like this,
$fields = array(
'method' => "methodGoPay",
'data'=> $xml_string_data // No encode here
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

Categories