Curl - how to handle the response - php

I am using this to send some info to another website and its working fine
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($post);
curl_close($post);
}
$data = array(
"api_key" => "****",
"api_password" => "****",
"notify_url" => "www.mysite.com",
"order_id" => "$orderid2",
"cat_1" => "$cat_1",
"item_1" => "$item1",
"desc_1" => "$desc_1",
"qnt_1" => "$qty1",
"price_1" =>"$up1",
"cat_2" => "$cat_2",
"item_2" => "$item2",
"desc_2" => "$desc_2",
"qnt_2" => "$qty2",
"price_2" => "$up2",
);
post_to_url("http://website2.com/submitorder.php", $data);
When website2 receives the info its sending back an xml responce "OK-Data Received" which appears on my page. Is there something I can do to stop this message being shown on my page so the person using the site doesn't see it?

You have to set the CURLOPT_RETURNTRANSFER setting :
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
That way, curl_exec($c) will return the output instead of passing it to the browser.
CURLOPT_RETURNTRANSFER
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

Set the option to:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Related

I'am getting error while sending SOAP web service a post requirest with cURL

I am trying to get info with soap web service but it is giving me an error Request format is invalid: multipart/form-data; boundary=------------------------b35e9c9f375db7a5.
$id = $_POST['id'];
$servicepassword = $_POST['servicePassword'];
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://webgov.com.tr/WebService/Kontrol.asmx/PasoSorguKontrol',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'id' => $id,
'servicepassword' => $servicepassword
],
CURLOPT_FOLLOWLOCATION => 1,
));
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
this web service need two variables to work, student id and web service password. and giving xml output. i could not make the code working. i am a newbie btw.
The solution is using CURLOPT_HTTPHEADER. I even make a function with this codes and it solved my problem.
function httpPost($url,$params) {
$postData = '';
foreach($params as $k => $v) {
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}

get data with CURL and JSON

i am trying to get data using Curl
i was trying to get best result but i got
but my goal to get specific line NOT all the lines.
see my code and please help to get the result with
"routing" AND "tot_dist" Other variables NO
here is my code
<?php
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
echo httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
// I WANT TO GET THE RESULT WITH ROUTING AND tot_dist ONLY LIKE THIS
//OOMS DCT KASIN DCT OOSA
//459.5
?>
This result i got
{"rc":"100","rmsg":"OK","gc_dist":459.2,"routing":"OOMS DCT KASIN DCT OOSA","tot_dist":459.5,"legs":[{"wt":"A","id":"OOMS","lat":"23.6002","lon":"58.2836","freq":"","via":"","brg":"0.0","dist":"0.0","name":"MUSCAT INTERNATIONAL"},{"wt":"W","id":"KASIN","lat":"20.3147","lon":"55.9617","freq":"","via":"DCT","brg":"214.7","dist":"235.8","name":"KASIN"},{"wt":"A","id":"OOSA","lat":"17.0387","lon":"54.0913","freq":"","via":"DCT","brg":"209.6","dist":"223.6","name":"SALALAH"}]}
but i need only "Routing" and "tot_dist"
Once you make a request, you will get all the data. You can then select what you need. Here is what your code should look like to select only routing and tot_dist
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt(
$ch, CURLOPT_HTTPHEADER,
array(
'Accept:application/json'
)
);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return json_decode($output,true);
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
$data = httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
echo $data['routing'] . "\n";
echo $data['tot_dist'] . "\n";

Trouble with POST API using cURL

I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

curl not redirecting as expected

Any idea why this function is not redirecting to paypal.com and instead I am staying on the same page? curl is activated on the server, safe mode is off and openbasedir is turned off too.
function curl_post($url, array $post = NULL, array $options = array())
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
curl_post("https://www.paypal.com/cgi-bin/webscr",$_POST);
Any idea what am I doing wrong?
After you make curl request:
foreach ($parameters as $key => $value) {
$requestParams[] = $key . '=' . $value;
}
$requestParams = implode ('&', $requestParams);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER);
curl_setopt( $ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);
You should get exact url, to know where you should be redirected:
$location = curl_getinfo($ch)['redirect_url'];
And then redirect:
header('Location: '. $location);
cURL is just a library for initiating and firing HTTP and FTP requests.
Your code just sends a HTTP POST request to the PayPal server.
In order to redirect the user, send a Location header (before any output!):
header('Location: https://www.paypal.com/...');

get amp; symbol using http_build_query

I am submitting some data from website1 to website2 using curl.
When I submit data via then on receiving end I get it like
Array
(
[ip] => 112.196.17.54
[amp;email] => test#test.com
[amp;user] => test123,
[amp;type] => point
[amp;password] => password
)
According to me http_build_query() producing wrong results.
"ip" field is correct rest are incorrect.
Please let me know why it happens.
curl function is given below: http_build_query($config)
function registerOnPoints($username ,$password,$email,$ip , $time )
{
$ch = curl_init("http://website2c.com/curl-handler");
curl_setopt(
$ch, CURLOPT_RETURNTRANSFER, 1);
$config = array( 'ip' => $ip,
'user' => $username,
'email' => $email,
'password'=> $password,
'time' => $time,
'type' => 'point') ;
# add curl post data
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($config));
curl_setopt($ch, CURLOPT_POST, true);
# execute
$response = curl_exec($ch);
# retreive status code
$http_status = curl_getinfo($ch , CURLINFO_HTTP_CODE);
if($http_status == '200')
{
$response = json_decode($response);
} else {
echo $http_status;
}
// Close handle
curl_close($ch);
}
If it is php version issue then, clearly speaking I have no permission to change the version of php because only the curl function is producing error rest project is completed and working as expected.
Please help me.
i guess you could try:
http_build_query($config, '', '&');
Or alternative:
$paramsArr = array();
foreach($config as $param => $value) {
$paramsArr[] = "$param=$value";
}
$joined = implode('&', $paramsArr);
//and use
curl_setopt($ch, CURLOPT_POSTFIELDS, $joined);

Categories