Mike
Mike

Reputation: 21

php if/else not working as expected

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">'; 
}
?>

Upvotes: 0

Views: 2721

Answers (3)

galchen
galchen

Reputation: 5290

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

Upvotes: 3

Mr Coder
Mr Coder

Reputation: 8196

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">'; 
}
?>

Upvotes: 0

Lucas
Lucas

Reputation: 10646

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
}

Upvotes: 0

Related Questions