PDA

Click to See Complete Forum and Search --> : [RESOLVED] Spanning an If statement across includes?


the182guy
Apr 7th, 2007, 07:00 AM
Im trying to avoid putting my login code on every page that needs authentication.

Is it possible to do something like have an include with an if statement which is left open so the rest of the page can exist inside my open else{, then at the end i will include a foot that just contains the } closing tag for the if?

heres my include

<?
//check login

if(!$logged_in){
echo("<p><strong>Error</strong><br />You need to be logged in to access this page. Click <a href='login.php'>here</a> to login</p>");
}else{
?>


So my page looks like:

<html>
blah
blah
<h1>Welcome</h1>

<? include("..assets/login_check_head.php"); ?>

THIS IS THE PROTECTED PAGE CONTENTS

<? include"..assets/login_check_foot.php ?>


blah
blah
</html>


But it throws an error saying unexpected $end in the include.

Any ideas? Or I will have to just insert this code into every page that requires login.

Cheers

penagate
Apr 7th, 2007, 07:35 AM
You cannot open a block in one file and close it in another.

What you can do is output your login form from the included page, and then call exit().

<!-- In a page requiring authentication -->
<?php require 'auth'; ?>

<!-- protected stuff here -->


<?php
// in auth file

if (!$logged_in) {
$pages['login']->show();
exit();
}
?>



You can make this all a lot more elegant if you a template mechanism to keep presentation (HTML) and logic (PHP) separate, which you should do in all non-trivial applications. If you do it this way, you can ditch the include altogether.

Something like:
<?php
// Grab the page required
$page = Master::page_from_uri([$_SERVER['REQUEST_URI']);

if ($page->requires_auth && !Auth::logged_in) {
Master::show_login_page($page);
}
else {
$page->show();
}
?>

the182guy
Apr 7th, 2007, 08:27 AM
Cheers, I'd like to do it that way but I've gotta finish this ASAP. I only have 3 or 4 pages that require login so I'll just stick the login code in there.