Divide the IF / ELSE statement between two php tags, give a Parse error: syntax error, unexpected end $

advertisements

I have built a PHP login system which starts session before loading each page and checks if the user is logged in.

On my Protected page I have a include at the top that starts the session and the if statement as to load the page or not. And then a the bottom I have another include which is the else statement redirecting back to the login page. This works fine when in the page direct, but when included from elsewhere I get this error: Parse error: syntax error, unexpected $end

This is the code

Include 1:

<?php

session_start();

if ($_SESSION['username'])
{
?>

THIS IS THE PROTECTED CONTENT THAT GETS LOADED IF SESSION EXISTS

Include 2:

<?php
}
else
header ("location: index.php");

?>

I think this might be caused by splitting the curly braces on the statement into two PHP tags, the reason why I have done this is to load a whole page if the if statement is true, rather than leaving it in PHP and echoing each line of HTML seperate.

How can I resolve this? or is there a better way for me to split the IF/ELSE statement.

Thanks Danny


Opening and closing curly brackets in between files is currently not possible. If you attempt to do this it will result in an "unexpected $end" syntax error.

I'm not sure what exactly you are shooting for but based on your comments you should be doing something like the following.

You should have 1 file you can name it whatever, but i'm just going to call it "allProtectedContent.php"

You said that there would be multiple files that need to be protected (which by that I assume you mean: multiple php files that need to be executed if the session exists). So inside of allProtectedContent.php you can include all the file files that you want to be executed/output.

Then in your main file you should simply have this:

<?php
if(isset($_SESSION['username']))
{
    include 'allProtectedContent.php';
}
else
{
    header('Location: index.php');
}
?>

So then anything you put in allProtectedContent.php will only be executed/output if the username key in $_SESSION is set.

Example of allProtectedContent.php:

<?php
// verify session
// echo some stuff
// include more files
// execute some functions
// run any php code you want
?>