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;
}
Related
So I have a php session timer that works but somehow gets bugged out after awhile... this is the code and the console log I got. I'm looking for a fix to this problem, or possibly a different set of code to achieve the same timer effect (as I'm not sure if using session is the best method for a timer)
session_start();
function timer($time) {
//Set the countdown to 120 seconds.
$_SESSION['countdown'] = $time*60;
//Store the timestamp of when the countdown began.
$_SESSION['time_started'] = time();
$now = time();
$timeSince = $now - $_SESSION['time_started'];
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);
$counter = 0;
$minutes = $remainingSeconds/60;
echo "$minutes minutes countdown starts.".PHP_EOL;
while($remainingSeconds >= 1) {
$now = time();
$timeSince = $now - $_SESSION['time_started'];
if (($timeSince-$counter) >= 60) {
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);
$counter = $timeSince;
$minutes = $remainingSeconds/60;
echo "$minutes minutes has passed.".PHP_EOL;
}
}
if($remainingSeconds < 1){
session_abort();
return true;
}
}
if($this->timer(30)) {
// do whatever
echo "$time has passed";
}
Here's what happens in the console:
30 minutes countdown starts.
29 minutes has passed.
.... (continue as per pattern)
16 minutes has passed.
15 minutes has passed. (problem occurs here)
8.7166666666667 minutes has passed.
7.7166666666667 minutes has passed.
6.7166666666667 minutes has passed.
.... (continue as per pattern)
0.71666666666667 minutes has passed.
0.28333333333333 minutes has passed.
1.2833333333333 minutes has passed.
2.2833333333333 minutes has passed.
.... (continue as per pattern all the way)
Extra notes: The session timer doesn't always recur this same pattern, there have been times when it ran through the entire 30minutes and managed to echo "$time has passed"; while the bug only occured later on
I haven't run your, but just from reading it I think there are a few things very wrong with it.
Sessions. You're not using them right.
Session values should only be set once, meaning before you do $_SESSION['countdown'] = $time*60; and $_SESSION['time_started'] = time();, you should check if they already exist or not, and only assign if nonexistent. Your current code resets the clock every time the page is refreshed, which defeats the purpose of sessions.
abs. I think you're not using them right either.
You shouldn't abs the remaining seconds all the time. $remainingSeconds = abs($_SESSION['countdown'] - $timeSince); should be allowed to go into negative. Negative remaining seconds mean your timeout has expired / you've missed it! Calling abs means you're effectively letting it go forever if you by any chance miss the exact time of your event. This is the answer to your main problem. Fix this and your counter will stop going to zero and back up again.
You're relying on your code correctly checking every single second. But it doesn't.
The nasty decimals you're getting happen when for some reason your code gets delayed and doesn't correctly check the 60th second, which means your division by 60 is not perfectly round and you get 8.7166666 minutes.
If you start by removing the abs calls and generally try to simplify your code a bit, I believe you'll quickly get it to work as intended.
// Edit 1
This is a very naive, but simplified approach to your problem. I left two different outputs in there for you to pick one.
function timer($time) {
echo "$time minutes countdown starts." . PHP_EOL;
// Save the date in future when the timer should stop
$endTime = time() + $time * 60;
// Keeps track of last full minute to simplify logs
$lastFullMinute = $time;
while(true) {
$timeRemaining = $endTime - time();
if ($timeRemaining <= 0) {
// Time remaining is less than zero, which means we've gone beyond the end date.
// End the loop
return;
}
// Round up!
$minutesRemaining = ceil($timeRemaining / 60);
if ($minutesRemaining != $lastFullMinute) {
// Current "minute" is different than the previous one, so display a nice message
// If you want to show how many minutes are remainig, use this:
echo "$minutesRemaining minutes remaining." . PHP_EOL;
// If you want to show how many minutes have passed, you have to take mintutesRemaining away from the original time
$minutesPassed = $time - $minutesRemaining;
echo "$minutesPassed minutes passed." . PHP_EOL;
$lastFullMinute = $minutesRemaining;
}
}
}
The main way for you to improve it further would be to use the sleep function http://php.net/manual/en/function.sleep.php. Currently the while loop will hog all the CPU by constantly checking if the timer happened, so you should sleep for a few seconds inside.
What do you think of this solution? referenced from above
function timer($time) {
echo "$time minutes countdown starts." . PHP_EOL;
// Save the date in future when the timer should stop
$endTime = time() + $time*60;
while(true) {
sleep(20);
$secondsRemaining = $endTime - time();
if ($secondsRemaining <= 0) {
echo 'Finished';
return true;
}
}
}
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
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);
How can I countdown for 7 hours from a variable time (I will get time from my table which is inserted with timestamp), after 7 hours from variable time I will update a table.
I need something like that
$time = 2013-05-18 02:00:00 // comes from database
$target = $time + 7hours // time from database +7hours will be 2013-05-18 09:00:00
$until = $target - $time
I need something like below code
if ($until > 0 ) {
echo "you need to wait for $until hours"
} else {
echo "time is ok"; // i will update a table
}
Convert time into string using strtotime($time)+25200 where 7 hour =60*60*7=25200 sec and then check and also add this file to your cron job.
So, considering that $database_time is the stored time, in your db, and $time_now is your computers time, this message below, just echoed out:
You Must wait 4 hours right, now
It could be done much better, but still calculates the hours from now, to db and tells you how much more, you must wait :)
<?php
$date = date_create();
$database_time = '2013-05-18 22:00:00';
$time_now = date_format($date, 'Y-m-d H:i:s');
$check = $database_time[11];
$check .= $database_time[12];
$check2 = $time_now[11];
$check2 .= $time_now[12];
$time_left = $check - $check2;
So, here is how you can manage your ourputs
if($time_left > 0) {
echo "You Must wait $time_left hours right, now";
}else{
echo "Time is OK";
}
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?