Tim Marshall
Tim Marshall

Reputation: 360

PHP Show Page If Cookies Are Set

Current Code

<?php
    $cookie_name = "testr";
    if(!isset($_COOKIE[$cookie_name])) {
        header("Location: http://admin.rafflebananza.com/authenticate.php");
        exit;
        } else { ?>

<!-- HTML PAGE GOES HERE -->

<?php } ?>

My current code looks like the above, but I've got a feeling this is not the way to do things as Dreamweaver says there is an error doing it this way.

What is the best way to redirect if the cookies have not been set before loading the page

Upvotes: 1

Views: 41

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270795

I'm not familiar with how Dreamweaver lints PHP code these days, but have often seen false positives on Stack Overflow where Dreamweaver reports syntax errors erroneously. The code and logic you have now is valid, if a little ugly.

Since the if() condition's action is to redirect away and explicitly exit, you actually have no need for the else {} block. You can directly follow the if () {} with the HTML content and PHP will output it because it has not already redirected away and terminated execution.

<?php
$cookie_name = "testr";
if(!isset($_COOKIE[$cookie_name])) {
    header("Location: http://example.com/authenticate.php");
    exit;
}
// No else {} block
// Follow this directly with your HTML    
?><!DOCTYPE html>
<html>
 <body>everything else...</body>
</html>

As has been pointed out in the comment thread, using a cookie alone as a guard for authentication is insufficient and not secure, unless the cookie's value can be validated with a secret in the code, like a one-time-use token. In that case, it may be more appropriate to store a value in $_SESSION which cannot be modified by the client browser.

Upvotes: 1

Related Questions