I am trying to show a success message before creating a PHP session and redirecting to another page. The problem is that if I use the sleep()
function, once I submit the form it just sleeps for 3 seconds and then redirects the same to the next page without showing the message. Here is the bit of code where I am having this trouble:
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!";
}
What you are trying to do can be done using JavaScript. Also as noted by the commenters, you may want to either have a button or write the message on the next page. It looks like the message isn't critical, so auto-disappearing is probably not a problem:
Option 1 - JavaScript Redirect:
Use essentially the same script you have now, but use javascript to redirect.
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;
Option 2 - Message to Next:
Assign the session and just redirect to the next page, then show the message on that page and auto-hide it on countdown (or not).
/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 ?>