在创建 PHP 会话和重定向之前显示消息

show message before creating PHP session and redirect

我试图在创建 PHP 会话并重定向到另一个页面之前显示一条成功消息。问题是,如果我使用 sleep() 函数,一旦我提交表单,它只会休眠 3 秒,然后将其重定向到下一页而不显示消息。这是我遇到这个问题的代码:

if(mysqli_query($connect, $query)){
    echo '<div class="alert alert-success" role="alert">Foi registado com sucesso!</div>';
    sleep(3);
    $_SESSION['email'] = $user_email;
    header("Location: areacliente.php");
}
}else{
    $erro .="O registo falhou!";
}

您尝试做的事情可以使用 JavaScript 来完成。同样正如评论者所指出的,您可能想要一个按钮或在下一页上写下消息。看起来这条消息并不重要,所以 auto-disappearing 可能不是问题:

选项 1 - JavaScript 重定向:

基本上使用与现在相同的脚本,但使用 javascript 进行重定向。

if(mysqli_query($connect, $query)):
    # Assign before message
    $_SESSION['email'] = $user_email ?>
    <!-- write message -->
    <div class="alert alert-success" role="alert">Foi registado com sucesso!</div>
    <!-- create timeout -->
    <script>
    setTimeout(function(){
        window.location = 'areacliente.php';
    }, 3000);
    </script>
<?php else:
    $erro .="O registo falhou!";
endif;

选项 2 - 给下一个留言:

分配会话并重定向到下一页,然后在该页面上显示消息并auto-hide倒计时(或不倒计时)。

/whatever_file_this_is.php

# Just set this as default false
$_SESSION['success'] = false;
if(mysqli_query($connect, $query)){
    # Set this to true for the next page
    $_SESSION['success'] = true;
    # Set the email as you have it
    $_SESSION['email'] = $user_email;
    # Redirect
    header("Location: areacliente.php");
    # Stop so rest of the script doesn't run
    exit;
}
else {
    $erro .="O registo falhou!";
}

/areacliente.php

<?php
# Check if the session success is true
if(!empty($_SESSION['success'])):
    # Remove it since it's being used now
    unset($_SESSION['success']); ?>
    <!-- Add an id to this div -->
    <div class="alert alert-success" role="alert" id="success-msg">Foi registado com sucesso!</div>
    <!-- count down and hide the message after 3 sections -->
    <script>
    setTimeout(function(){
        document.getElementById('success-msg').style.display = 'none';
    },3000);
    </script>
<?php endif ?>