countdown timer using php, can't make it work - php

i am making a php countdown timer that display only minutes and seconds.
here is my code:
$time = "10:00";
$time_min = substr($time, 0,2);
echo $time_sec = substr($time, 3) . "<br>";
$current = date("i:s");
$target = date("i:s" , mktime(0,$time_min,0,0,0,0));
echo $current-$target . "<br>";
echo $target;
the output should be the remaining time from the time the user opens the page.

Not knowing the details of your jQuery I am taking a shot at this.
I prefer working in seconds, so to get the $timeRemaining (you must know the initial time to do this) at any given instant in the 10 minute window, I would do this:
$targetTime = time() + 600; //you have to save this either in database or as variable somewhere
Then on subsequent opening of relevant php file the following code could be used if targetTime is saved in database
$sqlTime = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT targetTime FROM timeTable WHERE id = '$myID'"));
$currentTime = time();
$timeRemaining = (($sqlTime['targetTime'] - $currentTime) / 60) . ":" . (($sqlTime['targetTime'] - $currentTime) % 60);

Related

PHP - Deduct two timestamps from each other, display in minutes

I have a mySQL database that stores the checkin and checkout time of a person in a gym. I have imported the checkin and checkout times in to my PHP script. Now I want to deduct the two timestamps from each other - giving me the time left. I want this to display in minutes.
This is my idea:
$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
echo ($checkIn - $checkOut);
// I want this to display 31 minutes.
I have seen many examples on StackOverflow, but none matched my description and I couldn't reverse engineer the ones I found - because they use the time() function - which I guess takes the current time.
You can use strtotime();
$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value
$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn); // Converting to unix timestamp
echo date("i", ($checkIn - $checkOut)) . 'Minute(s)';
IMP Note: The above method will only work if the minutes are below 59, or else the hours will be rounded off and discarded. So if your requirements is showing the time in minutes which can be grater than 59 minutes eg. 144 minutes, then you'd want to just divide by 60, as follows.
$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value
$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn); // Converting to unix timestamp
$seconds = $checkOut_stamp - $checkIn_stamp;
if($seconds > 0){
if($seconds > 60){
$minutes = $seconds/60;
} else {
$minutes = 0;
}
} else {
$minutes = 0;
}
echo $minutes . ' Minute(s)';
$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
$time = (strtotime($checkIn) - strtotime($checkOut));
echo date('i',$time);
use this code
If you were fetching this record from database then you can simply achieve it using MySql function TIMESTAMPDIFF, as no need to use PHP function over here
Select TIMESTAMPDIFF(MINUTE,checkIn,checkout) as tot_diff from your_table

PHP Countdown Timer

Is it possible to create a timer using PHP so that after 60 seconds it does something. So it actually shows you a countdown from 60 to 0. I would refresh the div so it actually looks like it's counting down. I don't mind using JavaScript but I want to run the timer only when the $_GET variable is = to something.
For either option, can anyone help?
For now, I'm using this code I got from EpicSoftworks on Youtube but the problem with this code is that you have to specify the timestamp you want to use.
$future = -2211753540;
$current = time();
$difference = $future - $current;
$minutes = floor($difference/60);
$r_seconds = floor($difference - ($minutes = 60) );
echo '<h2>' . $minutes . ' - ' . $r_seconds . '</h4>';
use PHP to get the variable from the URL and then use javascript for the rest. Create a function that will run a loop 60 times. Inside that loop create a setTimeOut that will do something with a 1000 (1 second) timeout.

Add a random number every 24 hours

i need a script that automatically add a random number (between 1 and 5) every 24 hours and stores it in a text file, then after 24 hours creates a new random number and adds it to the previous result in the text file, i managed to do something close but still needs a refresh button to take effect, but i want it to automatically do it, so if 1 user visits the page every day, and one visits the page once a month, they should both see the same number (which will be read from the text file).
Here is my code so far:
<?php
$dataFile = "amt.txt";
$date1 = date("H:i:s");
$date2 = date("H:i:s",filemtime("amt.txt"));
$diff = abs(strtotime($date2) - strtotime($date1));
$secs = floor($diff);
if ($diff < 86400) {
echo "$date1 \n";
echo "$date2 \n";
printf($secs);
exit;
}
if (!file_exists($dataFile)) {
$amt = 0;
}
else {
// Otherwise read the previous value from
// the file.
$amt = (int) file_get_contents($dataFile);
}
// Generate the new value...
$Number = rand(1,5);
$total = $amt + $Number;
echo "$". $total ."/-";
// And dump it back into the file.
if (!file_put_contents($dataFile, $total)) {
// If it fails to write to the fle, you'll
// want to know about it...
echo "Failed to save the new total!";
}
?>
basically i want to show a fake number of subscribers which logically should increase with time. So i want to update the number on daily basis, then because i am having this on my website as the number of monthly subscribers, so when a user visits the website any time should see the same figure as any other user visitng the website on that exact time. Hope this is clearer now.
I'd first use time() instead date(xxx) so you get the diff secodns directly. But i don't get the purpose of this and don't know if you want to append the numbers or overwrite them, and also if the number changes every 24h why a user a month later should get the same number.
$date1 = time();
$date2 = filemtime("amt.txt");
$diff = $date1 - $date2;
if ($diff < 86400)
{
echo "$date1 \n";
echo "$date2 \n";
printf($diff);
exit;
}

How to get mysql data from table into php date()?

Title was wierd, yes. (Im norwegian)
Okay, I'm making a counter/timer to my new project and what it do is that when a user makes a action he/she must wait 100 sec before doing it again. But, how to get the timestamp (saved in mysql db) into the PHP code again and checking how long time since last time user checked to try again.
Some of my code (From the script):
// Waiting for time to go?
$sql = mysql_query("SELECT * FROM `crimes` WHERE user_id = '".$_SESSION["id"]."'");
$num = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
if($num == 1){ //Waiting
$time_now = date("H:i:s", strtotime("+100 seconds")); // This is where Im stuck, how to get that timestamp from mysql with 100 secs added?
$time_to_check = date("H:i:s", $row["time"]); // The time the action was done.
// This is where the code is going to check how long time since user visited.
} else {
}
So what Im asking for is that I need that one var that contains the data from mysql with 100 secs added, how? :)
This works:
$sql2 = mysql_query("SELECT UNIX_TIMESTAMP(time) AS time FROM `crimes` WHERE user_id = '".$_SESSION["id"]."'");
$row2 = mysql_fetch_array($sql2);
$seconds_ago = time() - $row2['time'];
$time_now = date("H:i:s", $seconds_ago + 100);
You can convert dates to UNIX timestamps in MySQL:
SELECT UNIX_TIMESTAMP(time) AS time FROM `crimes` ...
Then inside PHP:
$seconds_ago = time() - $row['time'];
$time = date("h:i:s", time() + 100);
$time_now = strtotime("now");
$time_to_check = strtotime($row["time"]) + 100;

Calculate elapsed time in php

Hi All I'm trying to calculate elapsed time in php. The problem is not in php, it's with my mathematical skills. For instance:
Time In: 11:35:20 (hh:mm:ss), now say the current time is: 12:00:45 (hh:mm:ss) then the time difference in my formula gives the output: 1:-34:25. It should actually be: 25:25
$d1=getdate();
$hournew=$d1['hours'];
$minnew=$d1['minutes'];
$secnew=$d1['seconds'];
$hourin = $_SESSION['h'];
$secin = $_SESSION['s'];
$minin = $_SESSION['m'];
$h1=$hournew-$hourin;
$s1=$secnew-$secin;
$m1=$minnew-$minin;
if($s1<0) {
$s1+=60; }
if($s1>=(60-$secin)) {
$m1--; }
if($m1<0) {
$m1++; }
echo $h1 . ":" . $m1 . ":" . $s1;
Any help please?
EDIT
Sorry I probably had to add that the page refreshes every second to display the new elapsed time so I have to use my method above. My apologies for not explaining correctly.
This will give you the number of seconds between start and end.
<?php
// microtime(true) returns the unix timestamp plus milliseconds as a float
$starttime = microtime(true);
/* do stuff here */
$endtime = microtime(true);
$timediff = $endtime - $starttime;
?>
To display it clock-style afterwards, you'd do something like this:
<?php
// pass in the number of seconds elapsed to get hours:minutes:seconds returned
function secondsToTime($s)
{
$h = floor($s / 3600);
$s -= $h * 3600;
$m = floor($s / 60);
$s -= $m * 60;
return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s);
}
?>
If you don't want to display the numbers after the decimal, just add round($s); to the beginning of the secondsToTime() function.
Using PHP >= 5.3 you could use DateTime and its method DateTime::diff(), which returns a DateInterval object:
$first = new DateTime( '11:35:20' );
$second = new DateTime( '12:00:45' );
$diff = $first->diff( $second );
echo $diff->format( '%H:%I:%S' ); // -> 00:25:25
Keep track of your time using the 'time()' function.
You can later convert 'time()' to other formats.
$_SESSION['start_time'] = time();
$end_time = time();
$end_time - $_SESSION['start_time'] = 65 seconds (divide by 60 to get minutes)
And then you can compare that to another value later on.
Use microtime if you need millisecond detail.
You can implement the solutions shown, but I'm fond of using the phptimer class (or others, this wheel has been invented a few times). The advantage is that you can usually define the timer to be active or not, thereby permitting you to leave the timer calls in your code for later reference without re-keying all the time points.
For high resolution time, try using monotonic clock: hrtime
<?php
$time = -hrtime(true);
sleep(5);
$end = sprintf('%f', $time += hrtime(true));
?>
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Categories