0

I need to make a page that has a timer counting down. I want the timer to be server side, meaning that when ever a user opens the page the counter will always be at the same time for all users. When the timer hits zero I need to be able to run another script, that does some stuff along with resetting the timer.

How would I be able to make something like this with php?

  • 1
    there must be two parts: a script in php which will show the time left (using current timestamp) and a js script to make ajax calls to that php script and update page contents – k102 Jan 28 '14 at 07:40
  • Okay. Will look into Ajax. I read somewhere about a language called Comet. Would it be possible to achieve this with that? – Thobias Nordgaard Jan 28 '14 at 07:41

2 Answers2

1

you can use Cron Jobs Ex: Scheduling a Job For a Specific Time 30 08 10 06 * /home/sendtouser.php 30 – 30th Minute 08 – 08 AM 10 – 10th Day 06 – 6th Month (June) * – Every day of the week

Medo Medo
  • 952
  • 2
  • 12
  • 21
  • I need to be able to show the timer countdown in a browser. When the timer is done it needs to run a script and then automaticly reset. Is this possible with a cron job? – Thobias Nordgaard Jan 28 '14 at 07:45
1

Judging from "when ever a user opens the page" there should not be an auto-update mechanism of the page? If this is not what you meant, look into AJAX (as mentioned in the comments) or more simply the HTML META refresh. Alternatively, use PHP and the header()

http://de2.php.net/manual/en/function.header.php

method, described also here:

Refresh a page using PHP

For the counter itself, you would need to save the end date (e.g. a database or a file) and then compare the current timestamp with the saved value.

Lets assume there is a file in the folder of your script containing a unix timestamp, you could do the following:

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>

You can use http://www.unixtimestamp.com/index.php to get familiar with the Unix Timestamp.

There are many ways that lead to rome, this is just one of the simple ones.

Community
  • 1
  • 1
x29a
  • 1,761
  • 1
  • 24
  • 43