dongquming3255 2018-03-28 19:56
浏览 66
已采纳

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

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!";
}
  • 写回答

1条回答 默认 最新

  • dongpa5277 2018-03-28 22:20
    关注

    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 ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?