CURL Unable to find error in code - php

<?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);

Related

not able to fetch json correctly from curl call?

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);

json post with cURL from a while loop

I am trying to post json data with cURL. The idea is: In case the url is not accessible ( for example failure of internet connection) keep trying to post the json while you succeed. It works but when I put it in while loop it executes only once. What am I doing wrong:
$jsonDataEncoded = json_encode($event);
echo $jsonDataEncoded;
echo "\n";
$send_failure = true;
while ($send_failure) {
$url = "a";// intentionally inaccessible url
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($jsonDataEncoded)));
$result = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
} else {$send_failure = false;}
return $result;
}
You must print and check the value in $result using var_dump($result); .
If there is any connection error it returns the error code which you can check manual in IF condition. Hope this might help you.

problems displaying json data retrieved using php curl

First, thanks for you reading. Here is my code
what my json data looks like when viewed in a browser using the url,
{
"$totalResults": 1500,
"$startIndex": 1,
"$itemsPerPage": 3,
"$resources": [
{
"$uuid": "5e7b9312-52e5-4fe1-b3e4-633ca04c9764",
"$httpStatus": "OK",
"$descriptor": "",
"name": "Heinz Tomato Sauce Sachets Qty 200"
},
{
"$uuid": "1a0f9dca-c417-4cff-94d2-99d16438723f",
"$httpStatus": "OK",
"$descriptor": "",
"name": "Heinz Brown Sauce Sachet Qty 200"
},
{
"$uuid": "126fdb17-81ce-41b4-bdba-91d0a170262a",
"$httpStatus": "OK",
"$descriptor": "",
"name": "Heinz English Mustard Sachets Qty 300"
}
]
}
test2.php
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&format=json';
//SAGE USERNAME & PASSWORD
$username = 'test';
$password = 'test';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$json = json_decode($result);
foreach ($json->{'$resources'} as $mydata) {
echo $mydata->name;
};
?>
errors im getting
Notice: Trying to get property of non-object in C:\xampp\htdocs\Sage Json\test2.php on line 29
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Sage Json\test2.php on line 29
I’m not sure what's going wrong, this works if i get the same data from a file but not if I’m retrieving it from at rest server, and if anyone could shed some light I would be grateful
Ajking11 the reason your getting Invalid argument supplied for foreach() is that $json vairiable is overwritten and has no data try somthing like this
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3';
//SAGE USERNAME & PASSWORD
$username = 'test';
$password = 'test';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$xml = simplexml_load_string($result);
$data = json_encode($xml);
$arr = json_decode($data,TRUE);
foreach ($arr['entry'] as $k=>$v){
echo $v; // etc.
}
note that I have removed &format=json and encoded later hope this help let me know how your getting on
you might like to use this code and refine it to your needs
<?php
// SAGE URL
//$url = 'http://computer_2:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&select=name&count=10&format=json';
$url ='http://localhost:5493/sdata/accounts50/GCRM/-/tradingAccounts?select=name&count=10';
//SAGE USERNAME & PASSWORD
$username = 'MANAGER';
$password = '';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$xml = simplexml_load_string($result);
foreach($xml->xpath("//sdata:payload") as $entry) {
// xpath here must be from payload to tradingAccount
$content = $entry->xpath("./crm:tradingAccount");
foreach($content as $c) {
// Make set of children with prefix crm
$nodes = $c->children('crm', true);
echo $nodes->reference . " | " . $nodes->name . " / " . $nodes->openedDate . "<br />\n";
}
}
thanks PHPhil and splash58 for your assistance with the namespace issue
As Artful_dodger say's the json is the problem here is how I would solve it
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&format=json';
//SAGE USERNAME & PASSWORD
$username = 'MANAGER';
$password = '';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
// doing a substring as there are 3 weird characters being passed back from IIS in front of the string
$json = json_decode(substr($result, 3, strlen($result)), true);
foreach ($json['$resources'] as $mydata) {
echo $mydata['name'] . "<br>";
}
PHP json_decode function returns an array and not an object, so instead of using
foreach ($json->{'$resources'} as $mydata) {
echo $mydata->name;
};
you should use
foreach ($json['$resources'] as $mydata) {
echo $mydata['name'];
};
UPDATE
your test2.php should look like this:
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&format=json';
//SAGE USERNAME & PASSWORD
$username = 'test';
$password = 'test';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$json = json_decode($result);
$json = (array)$json;
foreach ($json['$resources'] as $mydata) {
echo $mydata->name . "<br>";
};
in your code the major problem was in naming of the JSON attribute $resources: it is named as PHP variable and it causes the problem.
Converting the decoded variable into an array solves the problem as the associative array key is a string.
im really sorry for never getting back to you. so it turn out that when you get data from the sage service, it returned to you in "utf 8 bom".
So before i can display any thing i needed to remove the format by clearing the first three characters with in the array. with the substr() function.
$json_data = substr($json_data, 3);
Thank you all for helping with this problem.

$_POST via cURL not working

Im trying my hand at using curl to post some data, I am not reciving my post content and can not find the source of the problem
curl.php
<?php
$data = array("user_email" => "22" , "pass" => "22" );
$string = http_build_query($data);
$ch = curl_init("http://localhost:8888/290_project/test.php"); //this is where post data goes too, also starts curl
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch) //ends curl
?>
test.php
<?php
if(isset($_POST['user_email'], $_POST['pass'])) {
$name = $_POST['user_email'];
$pass = $_POST['pass'];
echo $name;
echo $pass;
} else {
echo "error";
} ?>
Every time I get my error response meaning the post data is not going through. I have tried everything I could think of to trouble shoot;I must be over looking something I am simply not yet familiar with?
Please set CURLOPT_URL to http://localhost:8888.....
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8888/290_project/test.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
if(!curl_errno($ch)){
$info = curl_getinfo($ch);
} else {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch) //ends curl
?>
With curl_getinfo() - Gets information about the last transfer.
For more detail read below link:- http://php.net/manual/en/function.curl-getinfo.php
I have edited the answer, The reason for error is not curl.
http_build_query($data, '', '&');
Following is working example. Please try this.
$postData = array(
'user_name' => 'abcd',
'password' => 'asdfghj',
'redirect' => 'yes',
'user_login' => '1'
);
$url='http://localhost:8888/290_project/test.php';
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $url);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$store = curl_exec($ch);
print_r($store);
curl_close($ch)
You have an error in your php code:
edit:
if(isset($_POST['user_email'], $_POST['pass'])) {
to:
if(isset($_POST['user_email']) && isset($_POST['pass'])) {

URL encode error?

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";
}
?>

Categories