A dummy script that reponds with some json..
<?php
$result['code'] = 200;
echo json_encode($result);
?>
However when I make a curl call to this script,trying to fetch json response and then convert it to array..things go wrong.
Usually I do a simple json_decode($json) and it gives me an array,but apparently when I var_dump json_decode($json) , it gives me int(1) as response. I simply want to fetch the code from the json.
This is my code :
public function curlcall($username, $msg)
{
$url = 'someurl.php';
$fields = array('username' => $username, 'message' => $msg);
$fields_string = null;
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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo '-------------------------';
var_dump($result);
exit;
}
When I directly call the script from rest client, it gives me perfect json response. But when I request the same json via curl, I dont get the desired result while converting that json in to array.
For simplicity sake, I just echoed a string but still when I var_dump it,it gives me int(1).
Try this:
$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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //NOTICE this line, which says you want a response returned to the calling script
$result = curl_exec($ch);
curl_close($ch);
echo '-------------------------';
var_dump($result);
Related
I am working on an getting a data from an api, on errors it responds with a JSON data but in success it redirects to a different url with get data variables and in that url contains the json success datas.
Is there work around on this on how i can get the success data without my page redirecting?
sample of the url when the response is success:
samplesite/api?message=0&code=0
$url = "urlprovided";
$fields = [
"Username" => "sample",
"Password" => "sample",];
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//execute
$result = curl_exec($ch);
$array = json_decode($result, true);
var_dump($array);
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;
}
<?php
$ch = curl_init("URL");
$username = "USERNAME";
$password = "PASSWORD";
$fields = array("from"=>array("name"=>"Bob","city"=>"SAINT-LAURENT","country"=>"CA","state"=>"QC","postal_code"=>"H4R1W4"),"to"=>array("is_commercial"=>true,"city"=>"ANJOU","country"=>"CA","state"=>"QC","postal_code"=>"H1J1Z4"),"packages"=>array("units"=>"imperial","type"=>"package","items"=>array("width"=>1,"height"=>2,"length"=>3,"weight"=>4)));
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
$data = curl_exec($ch);
if ($data === FALSE)
{
$temp=curl_error($ch);
echo "<p>cURL Error: {$temp}</p>";
}
echo "<pre>";
print_r($data);
curl_close($ch);
?>
Error I got is
{"error": "Unexpected input. Please make sure this is a valid JSON document"}
I'm unable to understand what this meant .
After Update the error i get is
Argument 1 passed to Support\ExposedObjectAbstract::setFromArray() must be of the type array, integer given, called in Shipping/Packages.php on line 22 and defined
Your server end point (the URL you're calling) requires the input to be a valid JSON. In order to do this, you can replace:
$field_string = http_build_query($fields);
with:
$field_string = json_encode($fields);
First set the HTTP header that you are sending JSON
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
And then, convert your array into JSON, and then setting to postfields
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
$field_string = http_build_query($fields); is what the problem is , try to pass as array
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
My PHP code (free.php) on http://techmentry.com/free.php is
<?php
{
//Variables to POST
$access_token = "b34480a685e7d638d9ee3e53cXXXXX";
$message = "hi";
$send_to = "existing_contacts";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freesmsgateway.com/api_send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('access_token' => $access_token,
'message' => urlencode('hi'),
'send_to' => $send_to,)
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
I am getting this error: THE MESSAGE WAS BLANK
This error means: "The message field was blank or was not properly URL encoded" (as told by my SMS gateway). But as you can see that my message field isn't blank.
I believe you can't send an array to CURLOPT_POSTFIELDS, you would need to replace the line with the following
curl_setopt($ch, CURLOPT_POSTFIELDS, "access_token=".$accesstoken."&message=".urlencode('hi')."&send_to=".$send_to);
I hope this solves it
Use http_build_query():
<?php
{
$postdata = array();
//Variables to POST
$postdata['access_token'] = "b34480a685e7d638d9ee3e53cXXXXX";
$postdata['message'] = "hi";
$postdata['send_to'] = "existing_contacts";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freesmsgateway.com/api_send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata) );
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
My code is:
<?php
extract($_POST);
$url = "http://www.domain.com/";
$fields = array(
'myparam1' => 'something',
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$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_RETURNTRANSFER, false);
$result = curl_exec($ch);
print_r("+");
curl_close($ch);
?>
The problem is it show the response in the web browse , but i dont want to. any help would be appreciated.
You have a comment on this line:
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, false);
You should enable this line and set the value to true
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
As you can see on the man page here that option is used this way:
TRUE to return the transfer as a string of the return value of
curl_exec() instead of outputting it out directly.
The option CURLOPT_RETURNTRANSFER will return the output rather than printing it.
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
CURLOPT_POSTFIELDS can take array directly and CURLOPT_RETURNTRANSFER should be true
$url = "http://www.php.net";
$fields = array(
'myparam1' => 'something'
);
// open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
I think this url will help you.
Get data or Content from a URL using cURL PHP