如何结合计时器和自动重定向? PHP

时间:2013-12-27 00:45:45

标签: php redirect timer

所以对于我的计时器页面,我试图找出如何使用这个PHP计时器进行重定向。它将从倒计时5显示在页面上,然后它应该执行脚本以访问给定的随机链接之一。

PHP计时器:

<?php
session_start();
$timestamp = time();
$diff = 5; //<-Time of countdown in seconds.  ie. 3600 = 1 hr. or 86400 = 1 day.

//MODIFICATION BELOW THIS LINE IS NOT REQUIRED.
$hld_diff = $diff;
if(isset($_SESSION['ts'])) {
    $slice = ($timestamp - $_SESSION['ts']);    
    $diff = $diff - $slice;
}

if(!isset($_SESSION['ts']) || $diff > $hld_diff || $diff < 0) {
    $diff = $hld_diff;
    $_SESSION['ts'] = $timestamp;
}

//Below is demonstration of output.  Seconds could be passed to Javascript.
$diff; //$diff holds seconds less than 3600 (1 hour);

$hours = floor($diff / 3600) . ' : ';
$diff = $diff % 3600;
$minutes = floor($diff / 60) . ' : ';
$diff = $diff % 60;
$seconds = $diff;


?>
<div id="strclock">Clock Here!</div>
<script type="text/javascript">
 var hour = <?php echo floor($hours); ?>;
 var min = <?php echo floor($minutes); ?>;
 var sec = <?php echo floor($seconds); ?>

function countdown() {
 if(sec <= 0 && min > 0) {
  sec = 59;
  min -= 1;
 }
 else if(min <= 0 && sec <= 0) {
  min = 0;
  sec = 0;
 }
 else {
  sec -= 1;
 }

 if(min <= 0 && hour > 0) {
  min = 59;
  hour -= 1;
 }

 var pat = /^[0-9]{1}$/;
 sec = (pat.test(sec) == true) ? '0'+sec : sec;
 min = (pat.test(min) == true) ? '0'+min : min;
 hour = (pat.test(hour) == true) ? '0'+hour : hour;

 document.getElementById('strclock').innerHTML = hour+":"+min+":"+sec;
 setTimeout("countdown()",1000);
 }
 countdown();

</script>

PHP重定向:

<?php
$num = Rand (1,3);
switch ($num) {
case 1: header('Location: http://RANDOMSITE1.COM');
break;
case 2: header('Location: http://RANDOMSITE2.COM');
break;
case 3: header('Location: http://RANDOMSITE3.COM');
break;
}
?>

我不赞成PHP计时器。我只是在需要它时查找不同的代码,这个我似乎无法弄明白。

1 个答案:

答案 0 :(得分:0)

当倒计时到达0时,您只需要转到重定向网址。

function countdown() {
    if (sec <= 0 && min > 0) {
        sec = 59;
        min -= 1;
    } else if (min <= 0 && sec <= 0) {
        min = 0;
        sec = 0;
    } else {
        sec -= 1;
    }

    if (min <= 0 && hour > 0) {
        min = 59;
        hour -= 1;
    }

    if (hour <= 0 && min <= 0 && sec <= 0) {
        document.location.href = "redirect.php";
    } else {
        var pat = /^[0-9]{1}$/;
        sec = (pat.test(sec) == true) ? '0' + sec : sec;
        min = (pat.test(min) == true) ? '0' + min : min;
        hour = (pat.test(hour) == true) ? '0' + hour : hour;

        document.getElementById('strclock').innerHTML = hour + ":" + min + ":" + sec;
        setTimeout(countdown, 1000);
    }
}
window.onload = countdown;