坏消息是 PHP 不能强制浏览器做任何事情。您需要带有 ajax 的 javascript 来实现这一点。但是如果在客户端禁用了javascript怎么办。 php有一个小技巧。
这是你可以做的。
通过执行
来确定直播开始的秒数
$numOfSeconds = $starttime - $currtime;
那么一旦你知道要在几秒后刷新浏览器,你就可以使用 php 来做到这一点。
header( "refresh:$numOfSeconds;urltoanywhere.php" );
这会将您带到您希望在特定时间后访问的任何网址。如果您想刷新,请定义指向同一页面的 url。你可以扩展这个逻辑来实现你想要的方式。
更新1:
下面是我测试过的工作代码。希望这对你有帮助:)
<?php
ob_start();
date_default_timezone_set('Europe/London');
$currentPage = $_SERVER['PHP_SELF'];
$currentTimestamp = strtotime(date('Y-m-d H:i:s'));
//Define your startTime here in {Year-Month-Day Hour:Minute:Second} format
$startTime = '2012-04-26 21:57:00';
//Define your endTime here in {Year-Month-Day Hour:Minute:Second} format.
$endTime = '2012-04-27 22:00:00';
$startTimestamp = strtotime($startTime);
$endTimestamp = strtotime($endTime);
$numOfSecondsToReload = $startTimestamp - $currentTimestamp;
if($currentTimestamp >= $startTimestamp && $currentTimestamp <= $endTimestamp):
?>
<a href="*broadcastlink*">LIVE NOW</a>
<?php else: ?>
<p>Live at <?php echo date('H:i', $startTimestamp); ?></p>
<?php header( "refresh:$numOfSecondsToReload;$currentPage"); ?>
<?php endif; ?>
Update2: 重新加载特定的 div 内容。这是您可以使用的代码。
<div id="live">
<?php
ob_start();
date_default_timezone_set('Europe/London');
$currentPage = $_SERVER['PHP_SELF'];
$currentTimestamp = strtotime(date('Y-m-d H:i:s'));
$startTime = '2012-04-27 12:42:20';
$endTime = '2012-04-28 22:00:00';
$startTimestamp = strtotime($startTime);
$endTimestamp = strtotime($endTime);
$numOfSecondsToReload = $startTimestamp - $currentTimestamp;
if($currentTimestamp >= $startTimestamp && $currentTimestamp <= $endTimestamp):
?>
<a href="*broadcastlink*">LIVE NOW</a>
<?php else: ?>
<p>Live at <?php echo date('H:i', $startTimestamp); ?></p>
<?php endif; ob_end_flush(); ?>
<div id="timeremaining" hidden><?php echo $numOfSecondsToReload * 1000; ?></div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var numOfMiliSecondsToReload = $('#timeremaining').html();
var timeToReload = (numOfMiliSecondsToReload >= 0) ? numOfMiliSecondsToReload : 86400000;
$(function() {
$(function() { setTimeout( reloadDiv, timeToReload ); });
function reloadDiv() { $('#live').load(location.href);}
});
</script>
希望对你有所帮助。