PHP function for Javascript redirect

The following code is basically JS, but has been made into a PHP function so that it could be invoked with different parameters as per our needs.

<?php
function js_redirect($url, $seconds=5) {
echo
“<script language=\”JavaScript\”>\n”;
echo
“<!– hide code from displaying on browsers with JS turned off\n\n”;
echo
“function redirect() {\n”;
echo
“window.location = \”" . $url . “\”;\n”;
echo
“}\n\n”;
echo
“timer = setTimeout(’redirect()’, ‘” . ($seconds*1000) . “‘);\n\n”;
echo
“–>\n”;
echo
“</script>\n”;

return true;
}

js_redirect(http://blogulate.com,1); //Redirects to blogulate.com in 1 second.

?>

Eg Usage :
js_redirect(http://google.com,5); //Redirects to Google after 5 seconds.



Search the Web with Google

6 Responses to “PHP function for Javascript redirect”


  1. 1 toraj

    what is this code? please say more about that
    thanks a lot

    1
  2. 2 thinkdj

    Hi toraj,
    Sorry about that. It’s a JavaScript echoed using PHP so that the destination URL and time before redirection could be called dynamically..
    Eg :

    js_redirect(http://google.com,5); //Redirects to Google after 5 seconds.

    js_redirect(http://google.co.in,15); //Redirects to Google.co.in after 15 seconds.

    2
  3. 3 toraj

    hello thinkdj
    so can i direct with this code myweblog to website ?

    3
  4. 4 thinkdj

    Toraj,
    I think the best for you would be a simpler META tag

    <meta http-equiv="refresh" content="0;URL=http://google.com">

    Just add this in the within the <head> </head> of your html. Change 0 to an integer value for time to wait before redirecting..

    4
  5. 5 thinkdj

    You could also view the source of the following page for another JS redirect:

    http://www.tizag.com/javascriptT/examples/timedelay.php

    5
  6. 6 Kirkorov

    Haha. It’s funny.

    6

Leave a Reply