php if / else没有按预期工作

时间:2011-09-17 12:54:45

标签: php if-statement

我是PHP的新手,无法弄清楚为什么这不能正常工作。我想要发生的是如果找到会话执行网页,否则重定向到login.php。发生的事情是网页正在执行,用户看到sql错误然后重定向发生。好像if和else都被执行了。请帮忙。

<?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 个答案:

答案 0 :(得分:2)

更好的方式:

<?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>

检查你的大括号并在使用会话之前进行session_start

答案 1 :(得分:0)

如果您在网页中使用if else语句,您可能会更容易找到此格式:

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

但是你的代码无法正常工作的原因是因为你的花括号混乱了。

检查此示例并将其与您的代码进行比较:

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

答案 2 :(得分:0)

尝试使用此代码,您的第一个简支括号正在关闭而不是打开

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