簡體   English   中英

php if / else沒有按預期工作

[英]php if/else not working as expected

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

一個更好的方式:

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

如果您在網頁中使用if else語句,您可能會更容易找到此格式:

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

但是你的代碼不起作用的原因是因為你的花括號混亂了。

檢查此示例並將其與您的代碼進行比較:

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

試試這個代碼你的第一個簡稱括號是關閉而不是打開

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM