OPNsense Forum

English Forums => General Discussion => Topic started by: col on May 09, 2019, 12:37:57 pm

Title: API Use with PHP
Post by: col on May 09, 2019, 12:37:57 pm
Hi All...

Not sure if this is the right board to post this in but here goes..

I'm trying to access the API's using a PHP script (only language I have some familiarity with) but struggling to get it to give any responses and the 'Help' documentation only shows examples in Python or cURL neither of which i'm familiar with, so got a bit stuck.

Here is the code i'm using (sensitive info removed), I've used similar code to get API's from other things before, so maybe i'm missing some syntaxing...

Code: [Select]
$api_key = "keyhere";
$api_secret = "secretehere";

$base_url = "https://<ip>/api";
$api_get_url = "/diagnostics/interface/getInterfaceNames";

$url_ints = $base_url.$api_get_url;

$get_opts = array('http' =>
    array(
        'method'  => 'GET',
        'header'  => 'auth='.$api_key.':'.$api_secret."\r\n" .'Content-Type: application/json'
    )
);

$get_context  = stream_context_create($get_opts);
$get_token = file_get_contents($url_ints, false,  $get_context);

$token_array = json_decode($get_token, true);

print_r ($token_array);

Any help would be appreciated.

Thanks!
Title: Re: API Use with PHP
Post by: franco on May 09, 2019, 12:46:39 pm
Hi there,

Basic auth needs to be properly encoded and advertised, see:

https://www.php.net/manual/de/function.stream-context-create.php#74431


Cheers,
Franco
Title: Re: API Use with PHP
Post by: col on May 09, 2019, 12:54:47 pm
Ahhh silly me.

Working now, thanks!
Title: Re: API Use with PHP
Post by: franco on May 09, 2019, 01:17:55 pm
Yay, nice  8)
Title: Re: API Use with PHP
Post by: SenseHH on June 13, 2019, 02:31:53 pm
It would be great if you could post the working script.

Thanks