Art-of-WiFi / UniFi-API-client

A PHP API client class to interact with Ubiquiti's UniFi Controller API
MIT License
1.13k stars 223 forks source link

$_SESSION['unificookie'] Example? #70

Closed Staja closed 4 years ago

Staja commented 4 years ago

Could you please include an example that utilises the $_SESSION['unificookie'] functionality? I can't get it to work.

malle-pietje commented 4 years ago

What exactly have you tried so far?

malle-pietje commented 4 years ago

A good example is our API Browser tool: https://github.com/Art-of-WiFi/UniFi-API-browser

Staja commented 4 years ago

I've tried setting $_SESSION['unificookie'] with get_cookies() after explicit login() but the next page request doesn't seem to utilise/load it.

malle-pietje commented 4 years ago

Can you share a code snippet showing what you did exactly and when?

Here you see how it’s done with the API Browser tool: https://github.com/Art-of-WiFi/UniFi-API-browser/search?q=unificookie&unscoped_q=unificookie

Staja commented 4 years ago

My workflow, albeit simplified:

$Unifi = new UniFi_API\Client(...);
if(!isset($_SESSION['unificookie'])) {
    if($Unifi->login()) {
        $_SESSION['unificookie'] = $Unifi->get_cookies();
    }
}

Is my mistake that I should be calling login() every time?

malle-pietje commented 4 years ago

Yes, calling the login method is always recommended but will be skipped if a cookie exists. No need to worry about it. I suggest you remove the outer if statement and see whether that helps.

Staja commented 4 years ago

Based on the Browser, I'm assuming I should be doing:

$Unifi = new UniFi_API\Client(...);
if($Unifi->login()) {
    $_SESSION['unificookie'] = $Unifi->get_cookies();
    ...
}

This seems to work now, I could have sworn I did that the first time but I saw that the unifises cookie value kept changing (due to building new sessions again and again?) so I thought I was doing it incorrectly...

malle-pietje commented 4 years ago

Since we don't know whether the cookie changes or not this approach is more reliable. Glad to hear it now works!