Reputation: 309
I just want to check if $_COOKIE
has my actual cookie or not.
On Stackoveflow I read a lot about not to use empty()
because it returns true
when 0 is given which could be the case for a cookie. And many more, see: LainIwakura's answer.
If my client tries to access a page and he has not a cookie, he should get blocked.
public function index($request, $response)
{
if($_COOKIE != " ") {
// Okay
} else {
return "Please log in first";
}
}
If I var_dump[$_COOKIE]
I get this:
array(0)
{
}
And when I log in first, I get this:
array(1) {
["AuthSession"]=>
string(44) "Ym9iOjU5ODhFN0E2Ov0k6qKicxKpkePKi1AjlXglURFm"
}
My if($_COOKIE != " ")
doesn't work and empty()
is also not a solution for this case. if(isset($_COOKIE))
is also not working, because there seems to be always an instance of this variable whether it is filled or not. Which kind of solution is left to check if the cookie is there or not from your opinion?
Upvotes: 0
Views: 844
Reputation:
The best way would be to check whether or not the actual cookie you're creating ('AuthSession') has been set, rather than checking if $_COOKIE is set or has a count > 0. If you haven't explicitly created that cookie, it will not be set, which is not the case with $_COOKIE.
public function index($request, $response)
{
if(isset($_COOKIE['AuthSession']) {
// Okay
} else {
return "Please log in first";
}
}
Upvotes: 2
Reputation: 1750
Use:
isset( $_COOKIE )
to see if it there is a cookie
Use
( count( $_COOKIE ) === 0 ) === FALSE
to check that it isn't empty
Therefore, your code should look like:
public function index($request, $response)
{
if( isset( $_COOKIE ) and ( ( count( $_COOKIE ) === 0 ) === FALSE ) ) {
// Okay
} else {
return "Please log in first";
}
}
Upvotes: 0