How to assign result fro curl to a variable? - php

I need to do a simple POST request and parse the result. For this i use curl in php. The problem is that i cant assign the result to a variable - it just prints .
My method:
private function sendRequest($data)
{
$ch = curl_init(self::IP . ':' . self::PORT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch); // HERE IT PRINTS
curl_close($ch);
$parsed_result = #simplexml_load_string(trim($result)); // OR HERE IT
die(var_dump(isset($parsed_result->request_error)));
if (isset($parsed_result->request_error))
$this->AJAXResult(TRUE, (string) $parsed_result->request_error->text);
}

You must add:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)
if you want curl_exec to return the result of the post request.

Related

JSON to PHP Array error

i am having trouble getting a JSON file to a php-array.
i got a json-file as response from an api (request done with curl)
and want to make an array out of it but it won't work.
Here is my code:
<?php
class modExpose{
public static function getFunction($id){
//In my code i am "preparing" the request here
// *********** cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$qry_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
}
$id = $_GET['id'];
$data = modExpose::getFunction($id);
$array = json_decode($data,true);
print_r($array);
?>
the print_r function only delivers: 1. (same does the var_dump() function).
I also tried adding html_entity_decode() but the problem still remains.
Thank's for helping!
That is probably because the return value of your curl_exec() call is true on success and that is all you are returning from your method.
If you want to get the data that was returned by the curl call, you need to set the CURLOPT_RETURNTRANSFER option:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$qry_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// Return the result on success
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
// Now response will contain the results of your curl call
$response = curl_exec($ch);
Apart from that I assume you have checked the variables that seem to be undefined in your example code.

PHP Curl request with http authentication and POST

I'm having trouble trying to get my code running. I'm trying to use cUrl with a post and http authentication but I'm unable to get it to work.
I'm using the following code:
public function index(){
$call = $this->call("URL_TO_CALL", $this->getCredentials(), $this->getJson());
}
private function getCredentials(){
return "API_KEY_HERE";
}
private function getJson(){
return $json;
}
private function call($page, $credentials, $post){
$url = "URL_TO_CALL";
$page = "/shipments";
$headers = array(
"Content-type: application/vnd.shipment+json;charset=utf-8",
"Authorization: Basic :" . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the POST to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
}
The response I'm getting is:
{"errors":[{"code":3001}],"message":"Permission Denied. (insertShipment)"}
I was expecting a list of shipments. Am I doing something obviously wrong here?
Looking at your code, you stipulate the URL in a variable then stipulate the exact page, however when you set the URL for the curl, you are merely using the URL variable as opposed to URL + PAGE variables.

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.

PHP CURL post returning results but I need empty results

I'm doing curl post but the problem is that I need to return empty results so I can echo out another value for my ajax request results:
below is the code:
$ch = curl_init("http://www.rankreport.com.au/ajax/add_new_lead");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "lead_company_id=1&lead_business=1234&lead_first_name=asdf&lead_website=12314.com&lead_phone=1234&lead_email=test#test.com&lead_package=seo");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
curl_close($ch);
echo 'error 3';
When I do this, I'm getting below results:
{"lead_date":1315637343,"lead_company_id":"1","lead_business":"1234","lead_first_name":"asdf","lead_last_name":"","lead_website":"12314.com","lead_phone":"1234","lead_email":"test#test.com","lead_package":"seo"} 3
How do set curl options so that it doesn't return any curl results?
Set CURLOPT_RETURNTRANSFER:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
Use CURLOPT_RETURNTRANSFER = true to have the returned content as a return value ($ch) instead of output.

Categories