Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
We have an auth cookie being set on login and removed on logout. Now we need to switch our authentication to use this cookie instead of the session.
Decoding the Cookie
function decodeAuthCookie($prop = null)
{
$cookie = json_decode(request()->cookies->get('auth'));
if ($prop === null) {
return $cookie;
}
if (!isset($cookie->$prop)) {
return false;
}
return $cookie->$prop;
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
We have an off cookie being set on login,
and removed on logout.
0:00
Now we need to switch our authentication
to use this cookie instead of the session.
0:06
Let's create a helper function to make
it easier to read the cookie properties.
0:12
Function DecodeAuthCookie().
0:17
Cookie = json_decode(request()
0:28
cookies->get('auth') and
0:36
return $cookie.
0:44
Let's call this new
function on our homepage.
0:48
We can remove those request and
call decondeAuthCookie.
0:54
Now let's go back to the browser.
1:03
Great, we can see both the auth,
user ID and the auth roles.
1:06
But what if we just want
to grab the user ID?
1:11
Let's go back to the function.
1:14
We're going to accept
a new optional argument.
1:19
Prop = null.
1:24
Then we're going to check if,
$prop === null,
1:29
Then we're just going
to return the cookie.
1:41
Next, we want to check if
1:45
(!isset($cookie->$prop)) then
1:50
we'll return false.
1:59
And finally we can return
2:03
the cookie $prop.
2:08
Four conditionals.
2:12
First we check if the property is null.
2:13
If so we're returning the whole cookie.
2:16
Next, if we have a property, we're going
to check if the cookie has that property.
2:19
If not, we're going to return false.
2:24
And finally, if both of those paths we
have an actual property on our cookie so
2:27
we will return that single property.
2:33
Now let's go back to our homepage.
2:36
And to our decodeAuthCookie,
we'll add auth_user_id.
2:39
Now we can go back to the browser.
2:45
And now, in the browser,
we see only the user ID.
2:50
Let's clean up the homepage.
2:54
We'll remove the var_dump and
then we can close the index.php.
2:59
Now we're ready to use this
new decode auth cookie.
3:05
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up