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?

2
  • 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 Commented Jan 28, 2014 at 7:40
  • Okay. Will look into Ajax. I read somewhere about a language called Comet. Would it be possible to achieve this with that? Commented Jan 28, 2014 at 7:41

2 Answers 2

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()

https://www.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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.