Paul Dessert
Paul Dessert

Reputation: 6389

How to delay code execution?

How can I delay the execution of a block of code in php?

    if ($qry->execute($leads)) {
    echo'<div class="note success">' . 
            $_POST["first_name"] . ', Your entry was successful!
        </div>';

        // Set up email params

This code displays a "Successful" message then emails the users. After displaying the the message, I want to redirect the user.

Is this possible in PHP? Do I need to use JavaScript?

Thanks!

Upvotes: 0

Views: 1935

Answers (3)

Dan
Dan

Reputation: 3870

PHP is a server-side language, which is executed before anything is shown to the user.

This is something that would have to take place after the page is rendered, so yes Javascript would be a better solution.

Upvotes: 2

nickb
nickb

Reputation: 59699

Since output has already occurred, you cannot do an HTTP Header redirection. Instead, you should set up a meta-refresh to redirect the user in the <head> of your HTML document:

<meta http-equiv="refresh" content="10;url=http://www.example.com/newpage.php" /> 

Upvotes: 3

user2428118
user2428118

Reputation: 8104

If you want to delay the execution of PHP code, you can use the sleep function. However, it appears that you want to delay a redirect for the client. You can do this with JavaScript, <meta> refresh and the Refresh header.

Using the Refresh header:

header('Refresh: «timeout in seconds»; URL=http://example.com/myurl');

Using <meta> refresh:

    <meta http-equiv="refresh" content="«timeout in seconds»; URL=http://example.com/myurl">

Using JavaScript:

setTimeout(function(){
 location.replace("/myurl");
},«timeout in milliseconds»);

The best is to use a combination of these three, and also show a message for users that have disabled these redirection technologies with a link that allows them to click through manually.

Upvotes: 13

Related Questions