Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Delay on redirect

Tags:

redirect

php

I'm using the following code to use as a form of nulling referring script and it works perfectly but it just redirects them straight to the target URL.

How would I go about creating a 5 second delay so I can display some adverts for 5 seconds before redirecting them?

like image 210
CustomNet Avatar asked Feb 19 '13 10:02

CustomNet


3 Answers

You can send php header with timeout refresh. http://php.net/manual/en/function.header.php

<?php 
  header( "refresh:5; url=wherever.php" ); 
?>
like image 155
Vahe Shadunts Avatar answered Oct 11 '22 04:10

Vahe Shadunts


What about using sleep()?

function method1(...) {

sleep(5);

... rest of the code

Note however that it is more recommended to use Vahe Shadunts's answer, which uses header() instead.

like image 29
fedorqui 'SO stop harming' Avatar answered Oct 11 '22 04:10

fedorqui 'SO stop harming'


The refresh header does the job but I'd like to highlight some potential issues:

  • It is not specified in the HTTP standard. Wikipedia says:

    Proprietary and non-standard: a header extension introduced by Netscape and supported by most web browsers.

    But it has been around for almost 20 years now and I don't know of any browser that does not support it (could not find a reference though)

  • Some browsers do not use the cache on a page redirected with refresh. It has been demonstrated for Internet Explorer here: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/meta-refresh-causes-additional-http-requests.aspx and I coud reproduce it on Firefox. Chrome does not have this issue.

Alternative: JavaScript

You can add a JavaScript on the intermediate page, that opens a new page after X seconds. Add this at the bottom of the page to redirect to http://www.example.com/target after 5 seconds:

<script type="text/javascript">
    window.setTimeout(function() {
        window.location.href='http://www.example.com/target';
    }, 5000);
</script>

Combination

As a bonus, you can fall back to the refresh header if JS is disabled, using the meta directive http-equiv that tells the browser to act as if a certain HTTP header has been sent. Because it is part of the HTML source, you can wrap it in a <noscript> element. Add this to your <head> additionally to the JavaScript above:

<noscript>
    <meta http-equiv="refresh" content="5;url=http://www.example.com/target" />
</noscript>

Now, the page redirects with JavaScript if available for the best performance, and uses refresh otherwise.

like image 32
Fabian Schmengler Avatar answered Oct 11 '22 04:10

Fabian Schmengler