0

I am new to PHP and cannot figure out why this is not working properly. What I want to happen is if a session is found execute the web page otherwise redirect to login.php. What is happening is the webpage is being executed and the user sees sql errors then the redirect happens. It's as if both the if and the else are being executed. Please help.

<?php
if (isset($_SESSION['userID']))
{
$mainUID=$_SESSION['userID'];
?>
<body>

The entire webpage is in here but removed it for a short example.

</body>
</html>

<?
}
else
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=login.php">'; 
}
?>
3
  • check your braces near the if. also do session_start() before Commented Sep 17, 2011 at 12:57
  • Thank you everyone. I made an error in my original post, I apologize. The curly braces are correct in my code not in my question. I also started my session as the very first line. <?php session_start(); ?> Commented Sep 17, 2011 at 13:03
  • Thank you everyone!! It is working properly now I really appreciate all of your help!! Commented Sep 17, 2011 at 13:15

3 Answers 3

3

a nicer way:

<?php
session_start();
if (!isset($_SESSION['userID'])){
    header("Location: /login.php");
}
$mainUID=intval($_SESSION['userID']);

?>
<html>
<body>
The entire webpage is in here but removed it for a short example.
</body>
</html>

check your braces and do session_start before using the session

Sign up to request clarification or add additional context in comments.

3 Comments

An even nicer way is to remember to put die() after the header(), so you are not sending any more content along with the redirect.
no doubt. also i normally create my own redirect function that prints out a simple html page with meta redirect and js redirect. another thing is use output buffer to make sure not content is flushed before the headers. thanks for the input
You should use an absolute URI as argument 'Location' (including the scheme, hostname and absolute path).
0

If you are using if else statements within a webpage you may find this format easier:

<?php if(true): ?>
    HTML Here
<?php else: ?>
    HTML Here
<?php endif; ?>

But the reason why your code isn't working is because you have got your curly braces mixed up.

Examine this example and compare it with your code:

if(true) {
    // Do stuff
}
else {
    // Do stuff
}

1 Comment

Thank you everyone!! It is working properly now I really appreciate all of your help!!
0

Try this code your first curtly bracket was closing instead of opening

<?php
if (isset($_SESSION['userID']))
{
$mainUID=$_SESSION['userID'];
?>
<body>

The entire webpage is in here but removed it for a short example.

</body>
</html>

<?
}
else
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=login.php">'; 
}
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.