我想在创建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!";
}
答案 0 :(得分:1)
您尝试做的事情可以使用JavaScript完成。同样如评论者所述,您可能想要一个按钮或在下一页上写下消息。看起来消息并不重要,因此自动消失可能不是问题:
选项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 - 下一封邮件:
分配会话并重定向到下一页,然后在该页面上显示该消息并在倒计时(或不是)时自动隐藏它。
<强> /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 ?>