When using PHP's curl API, if I accidentally use a string with the CURLOPT_HTTPHEADER curl option
curl_setopt($ch, CURLOPT_HTTPHEADER, 'User-Agent: php-curl');
PHP will scold me
Warning: curl_setopt(): You must pass either an object or an array with the CURLOPT_HTTPHEADER argument in /path/to/test.php on line 32
I know I can fix this using an array
$headers = [];
$headers[] = 'User-Agent: php-curl';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
However, the warning seems to indicate I could also be passing curl_setopt an object. Is this possible?
I've tried with both an stdClass and ArrayObject, but neither seems to work. Is this just a misleading warning message, or is there a way to use curl_setopt with an object?
Update Turns out I had a PHP extension installed that was blocking the standard behavior. ArrayObjects work fine in this function. I can't close or delete this question, so hopefully this warning will avoid confusion.
You need to pass an object that implements JsonSerializable.
class Testing implements JsonSerializable
{
protected $headers = [];
public function __construct($headers)
{
$this->headers = $headers;
}
public function jsonSerialize()
{
return $this->headers;
}
}
Then you can pass it to your CURLOPT_HTTPHEADER parameter:
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, new Testing(['User-Agent: php-curl']));
Related
I am trying to get a response from MPESA payment API using laravel but I am getting an error . My code is as below
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MPESA_AUTH extends Controller
{
public function Authorize(){
$url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$CONSUMER_KEY= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$CONSUMER_SECRET= 'xxxxxxxxxxxx';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
$credentials = base64_encode($CONSUMER_KEY,$CONSUMER_SECRET);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.$credentials)); //setting a custom header
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$curl_json=json_decode($curl_response);
return $curl_json;
}
}
The error am getting is as below
The Base controller uses Illuminate\Routing\Controller trait which has an 'authorize()' function. Your function declaration is clashing with it.
Change your controller method name to anything else(other than 'authorize') and you should be good to go
You should use a different function name in place of "Authorize". This is because "authorize" in controllers is a preserved name used in the parent class Controller.
I want to fetch data from Third_party API called BirdEye. I was using Core PHP Inbuilt Functions of CURL to fetch data, it was working fine, Now When I switched to Library I am bit confused because it doesn't gives me any response in return.
I have Downloaded Curl Libray from Here : Curl Library Download and Example
I tried to create a demo just to check my Library is working fine or not, it worked. Now If I fetch data from Bird-Eye Api I don't know It gives me nothing in response.
My Code is here:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('curl');
$get_url = "https://api.birdeye.com/resources/v1/business/147802929307762?api_key=ApiKeyGoesHere";
echo $this->curl->simple_get($get_url, false, array(CURLOPT_USERAGENT => true));
echo $this->curl->error_code;
$this->load->view('welcome_message');
}
}
I don't know where I am going wrong I am passing all the required parameters to the Api and when I try to echo error code it gives me 22. I even searched on birdeye documentation but nothing found.
Link to Api Documentation is : Link to BirdEye Api Documentation
So according to the BirdEye API your cURL script should be like the following:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.birdeye.com/resources/v1/business/businessId ");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
Now, when I'm comparing your library usage code to the example above, I see you're missing the definitions of several options.
Before adding those options to your code, try to follow this part:
In the example they're not using the APIKEY, but when you do use it, you might need to pass it as a parameter and not in the get_url variable.
Which means:
$get_url = "https://api.birdeye.com/resources/v1/business/147802929307762";
echo $this->curl->simple_get($get_url, array('api_key' => 'YourApiKeyGoesHere'), array(..));
If it still doesn't work, try to add the options to your code:
$this->load->library('curl');
$get_url = "https://api.birdeye.com/resources/v1/business/147802929307762?api_key=ApiKeyGoesHere";
echo $this->curl->simple_get($get_url, false, array(CURLOPT_USERAGENT => true, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HEADER => FALSE, CURLOPT_HTTPHEADER => array("Content-Type: application/json", "Accept: application/json")));
echo $this->curl->error_code;
$this->load->view('welcome_message');
I am using the curl option CURLOPT_HEADERFUNCTION along with a closure to perform some basic data manipulation. As per the php docs, the function / callback must return the length of the header on each call.
$headers = [];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function($curl, $headerLine) use (&$headers) {
$headers[] = $headerLine;
return strlen($headerLine);
});
$response = curl_exec($curl);
curl_close($curl);
return $headers;
I am using references to return the value which works fine. I am just curious if there are other ways to return this value without using references or using a callback?
You can specify the callback function to be a class method:
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array($this, 'someOtherFunction'));
In that other function, you can have access to anything $this has access to:
protected function someOtherFunction($curl, $headerLine)
{
$this->headers[] = $headerLine;
return strlen($headerLine);
}
* This answer assumes you're inside of a class context to begin with
I've got an app which works with Digits as authentication.
Client-side works perfectly, but I'm not able to make the server user authentication through oAuth.
My server is developed with Laravel, so it's PHP.
My endpoint is under https, so everything should be ready to make the call.
I solved by myself!
Here's the code that makes correctly the authentication through Digits O-Auth.
The function that makes authentication is inside an AuthManager class and I call in this way:
$obj = AuthManager::verifyUser($request->header('X-Auth-Service-Provider'),$request->header("X-Verify-Credentials-Authorization"));
And here's the function that makes the magic:
public static function verifyUser ($xAuthServiceProvider, $xVerifyCredentialsAuthorization)
{
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $xAuthServiceProvider);
curl_setopt($curl,CURLOPT_HTTPHEADER, array(
'Content-length: 0',
'Content-type: application/json',
'Authorization: '.$xVerifyCredentialsAuthorization,
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
$obj = json_decode($content, true);
return $obj;
}
If you have any problem, don't hesitate to write here!
EDIT WITH EXAMPLE FUNCTION ABOUT HOW TO GET DATA FROM O-AUTH
public function authenticate (Request $request)
{
$obj = AuthManager::verifyUser($request->header('X-Auth-Service-Provider'),$request->header("X-Verify-Credentials-Authorization"));
if(isset($obj["errors"]))
{
return "error!";
}
$digits_token = $obj["access_token"]["token"];
$digitsId = $obj["id"];
/*
the variables above are returned by O-auth server-server authentication
*/
}
I would like to call a rest function of my api with the GET protocol but I didn't succeed to put the security key of restler as a post parameter.
example:
/index.php/myrestapi/method.json?name=test
post field : Array('key'=>'mykey')
$session = curl_init('<mydomainurl>/index.php/myrestapi/method.json?name=test');
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, array('key'=>'mykey');
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($session);
Myrestapi.php function:
protected function getMethod($name){
return $name;
}
What is wrong?!
Thanks in advance for your help!
Kevin
security key should also be part of get parameter
<mydomainurl>/index.php/myrestapi/method.json?name=test&key=mykey
Then need to handle that with iAuthenticate.
For more details see e.g. Protected API of restler.