PHP CURL call is displaying NULL all the time - php

This question has been asked. But any of those didn't work out for me. I am getting NULL when CURL call is made all the time.
The following is my list_clients.php file.
<?php
require_once 'init.php';
header('Content-Type: application/json');
$clientResults = mysqli_query($link, "SELECT * FROM clients");
$clients = array();
while($client = mysqli_fetch_assoc($clientResults)){
$clients[] = $client;
}
echo json_encode($clients);
exit;
So the output of the above is :
[{"ip_address":"192.168.177.137","mac_address":"3a:1a:cf:7c:92:89","added_on":"2017-08-19 12:48:34"},{"ip_address":"192.168.177.137","mac_address":"3a:1a:cf:7c:92:89","added_on":"2017-08-20 08:09:29"}]
The following is my curl_call.php file
<?php
$url = 'http://127.0.0.1/testing/list_clients.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
curl_setopt($curl, CURLOPT_HEADER, 0);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type : application/json',
'Accept: application/json'
));
$clientResult = curl_exec($curl);
if($clientResult == FALSE) {
var_dump(curl_error($curl));
}
curl_close($curl);
var_dump($clientResult); //For this line I am getting the following image eror
$clients = json_decode($clientResult, TRUE);
var_dump($clients);
If I var_dump($clientResult); then I am getting the following error
It's displaying NULL all the time. What might be causing the error.

You are missing a warning being thrown about $ch. It's undeclared, yet you reference it on line 17:
if($clientResult == FALSE) {
var_dump(curl_error($ch));
}
(As a side note, I'd use === FALSE, so valid return values which cast to FALSE don't wrongly trigger that code.)
You're also then carrying on with execution after the error is (failed to be) handled. The NULL you're seeing could be because the curl request failed.
Correct the typo in your code and stop (or do appropriately) if an error is thrown:
if($clientResult == FALSE) {
var_dump(curl_error($curl));
exit();
}
Update in response to the OP being updated:
The other reason NULL might be returned is because the response is not valid json. Check the PHP documentation:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
That HTML output you're debugging now shows (in your question update) won't parse as JSON.

Just now figured out. If I comment the following line of code in the curl_call.php it will work fine.
<?php
$url = 'http://127.0.0.1/testing/list_clients.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
/* curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type : application/json',
'Accept: application/json'
)); */
$clientResult = curl_exec($curl);
if($clientResult == FALSE) {
var_dump(curl_error($curl));
}
curl_close($curl);
var_dump($clientResult);
$clients = json_decode($clientResult);
var_dump($clients);

Related

PHP Curl get data

I'm created a simple PHP curl client that call a external webservice. This webservice return the XML.
<?php
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$response = CallAPI('GET','https://s1-en.ogame.gameforge.com/api/universes.xml');
var_dump($response);
//print string(1121) " "
?>
But it always gives me back the wrong value. I print string(1121) " ".
How can I get the call data? (line 41 in the test.php).
This is because you are viewing the result in browser and the browser parses the xml as valid html tag. So you get empty result.
Its not your code issue. you can press ctrl + u (view source) in browser to see the actual result.
Or you can edit your var_dump to echo htmlentities($response); on line 41.

php curl_exec returns response as 1

I am trying to use curl as below code snippet. I already tried all options i could search for the similar issue. have added all setopt options availabale but still i get response as 1. I am trying post request to server and expecting json response. What am I missing?
$logger->info('url:'.$service_url);
$curl = curl_init();
$curl_post_data = array(
'username' => 'user1',
'password' => 'welcome'
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS,$curl_post_data);
curl_setopt($curl, CURLOPT_URL, $service_url);
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($curl,CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$logger->info('curl_response 11:'.print_r($curl_response));
$decoded = json_decode($curl_response,JSON_PRETTY_PRINT);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
$logger->info('response ok!');
$logger->info('decoded:'.print_r($decoded));
Updated for solution:
as suggested just used print_r($curl_response, true) to log the response, and used print_r($decoded['orderId']) to get the specific values.
print_r() prints its output, it doesn't return it. In order to store the output of a call to print_r() in a variable, or send it to a logger or whatnot, you need to pass a truthy value as the second parameter.
$x = print_r($foo); // prints formatted $foo and returns true
$x = print_r($foo, true); // prints nothing and returns formatted $foo
Note: Since you've set CURLOPT_RETURNTRANSFER to true, the call to curl_exec() will already return a string. There's really no need to pass that through print_r(), just dump the string.
Also note: You'll want to verify that json_decode() doesn't return null. And you'll likely also want to verify that the HTTP status code is 200 (which you can do via curl_getinfo().

PHP JSON parsing with cURL

I want to create a simple page that prints the region you are in, I am using an API from this site freegeoip.net. I have it set up so it runs a users ip through the site and returns JSON, however I am having issues parsing that response. This is the code I have written:
<?php
$person = $_SERVER["REMOTE_ADDR"];
$url = "freegeoip.net/json/$person";
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
$json = json_decode($result, true);
echo $json['region_name'];
echo $json['city'];
?>
However for some reason, it still prints the full response from the server API... how do I fix this?
Add the following line after setting CURLOPT_HTTPHEADER:
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
By default curl_exec() outputs the response out directly and it returns TRUE on success or FALSE on failure. If you set CURLOPT_RETURNTRANSFER to TRUE, curl_exec() will return the actual result of successful operation, but still will return FALSE on failure.

Displaying curl data, blank page

I'm trying to download json data using curl in PHP from companies house API.
Here is the example they provide that I'm trying to use:
https://developer.companieshouse.gov.uk/api/docs/company/company_number/readCompanyProfile.html#here
The example:
curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: https://api.companieshouse.gov.uk/company/{company_number}
My code
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.companieshouse.gov.uk/company/01000000");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'curl -u8yUXrestOfmyApiKey:'
));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($curl);
if(false == $result){
echo curl_error($curl);
}
curl_close($curl);
print($result);
?>
Using header:
'-u my_api_key:8yUXGgcHznjaNWnKpuKIJ7yv7HDvU_slH273GuF1'
I get 400 - bad request and with header in my code above I get nothing no errors blank page no data.
PS. There is a company with number 01000000 I've checked
You shuld add CURLOPT_USERPWD
curl_setopt($curl, CURLOPT_USERPWD, "YOUR API KEY"); #Add your api key

PUT Request via CURL

I'm trying to make an CURL PUT REQUEST, my code looks like:
public function assignProfile($token, $organizationId, $profileId)
{
//define enviroment and path
$host = enviroment;
$path = "/admin/organizations/".$organizationId."/users";
$data_string = '["'.$profileId.'"]';
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$token.'',
'Content-Length: ' . strlen($data_string)
));
echo "<br>OK<br>";
// execute the request
$output = curl_exec($ch);
// return ID for a new case
$output = json_decode($output);
var_dump($output);
}
Each part looks correct, when I var_dump $path, $host, even $data_string looks correct. However var_dump() at the end throw just NULL
I expect I'm doing something wrong or missing something really important.
May I ask you for some advise?
Thanks
EDIT:
What i do with it:
// define
define("Audavin","here is some uniqe ID");
.
.
.
$Users = new Users;
// this return Auth token ( I verify this work with echo )
$token = $Users->authorization();
// Calling method mentioned above
$Users->assignProfile($token,"here is org id", Audavin);
I would start by making sure the URL you're making the request to actually works and returns a valid response, you can do so by using a simple REST client (like POSTMAN chrome extension for example)
If you do get a response back, try and see if it's indeed a valid JSON, if not, that could be why you're not getting anything back from json_decode (more on return values here: http://php.net/manual/en/function.json-decode.php)
Finally, It is suggested you add curl_close($ch) to the end of your code to make sure your release the curl handle.

Categories